以下是代码。
首先,我尝试分配并释放一个大块内存,然后我分配许多小块内存,直到内存用尽,并释放所有这些小块。
之后,我尝试分配一个大块内存。
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
static const int K = 1024;
static const int M = 1024 * K;
static const int G = 1024 * M;
static const int BIG_MALLOC_SIZE = 1 * G;
static const int SMALL_MALLOC_SIZE = 3 * K;
static const int SMALL_MALLOC_TIMES = 1 * M;
void **small_malloc = (void **)malloc(SMALL_MALLOC_TIMES * sizeof(void *));
void *big_malloc = malloc(BIG_MALLOC_SIZE);
printf("big malloc first time %s\n", (big_malloc == NULL)? "failed" : "succeeded");
free(big_malloc);
for (int i = 0; i != SMALL_MALLOC_TIMES; ++i)
{
small_malloc[i] = malloc(SMALL_MALLOC_SIZE);
if (small_malloc[i] == NULL)
{
printf("small malloc failed at %d\n", i);
break;
}
}
for (int i = 0; i != SMALL_MALLOC_TIMES && small_malloc[i] != NULL; ++i)
{
free(small_malloc[i]);
}
big_malloc = malloc(BIG_MALLOC_SIZE);
printf("big malloc second time %s\n", (big_malloc == NULL)? "failed" : "succeeded");
free(big_malloc);
return 0;
}
以下是结果:
big malloc first time succeeded
small malloc failed at 684912
big malloc second time failed
看起来似乎存在内存碎片。
我知道当内存中有许多小的空闲空间,但没有足够大的空闲空间来进行大块的malloc时,就会发生内存碎片。
但是我已经释放了所有我分配的内存,内存应该是空的。
为什么第二次我无法进行大块的malloc?
我在Windows 7上使用Visual Studio 2010构建32位程序。
free()
循环会在遇到第一个NULL
时终止。 - unwind