【发布时间】:2014-07-17 10:38:14
【问题描述】:
这里是代码。
首先我尝试 malloc 并释放一个大块内存,然后我 malloc 很多小块内存直到它耗尽内存,然后我释放 所有这些小块。
之后,我尝试 malloc 大块内存。
#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,内存应该是空的。
为什么我不能第二次 malloc 大块?
我在 Windows 7 上使用 Visual Studio 2010,构建 32 位程序。
【问题讨论】:
-
可能内存还是碎片化的。您是否尝试过在程序运行时监控内存发生了什么?
-
@DieterLücking 我也这么认为,但是
free()-loop 在遇到第一个NULL时结束。 -
@DieterLücking 当 smalloc malloc 失败时, malloc 返回 NULL。在第二个 for 循环中,我检查 small_malloc[i] != NULL 以保护未初始化的指针。
-
显然,VC++ 无法重新组合相邻的空闲内存块。在 32 位 Linux 上使用 GCC,它可以工作。
-
问题不是VC++而是libc的堆管理器。默认情况下,windows 的堆管理器非常保守,但是有一个 API 可以请求使用新的堆管理器
标签: c++ c windows heap-memory fragmentation