我有一个内存碎片问题,可以在这个小例子中总结:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
void *p[8000];int i,j;
p[0]=malloc(0x7F000);
if (p[0]==NULL)
printf("Alloc after failed!\n");
else
free(p[0]);
for (i=0;i<8000; i++) {
p[i]=malloc(0x40000);
if (p[i]==NULL){
printf("alloc failed for i=%d\n",i);
break;
}
}
for(j=0;j<i;j++) {
free(p[j]);
}
/*Alloc 1 will fail, Alloc 2 *might* fail, AlloC3 succeeds*/
p[0]=malloc(0x7F000);
if (p[0]==NULL)
printf("Alloc1 after failed!\n");
else {printf("alloc1 success\n");free(p[0]);}
p[0]=malloc(0x40000);
if (p[0]==NULL)
printf("Alloc2 after failed!\n");
else {printf("alloc2 success\n");free(p[0]);}
p[0]=malloc(0x10000);
if (p[0]==NULL)
printf("Alloc3 after failed!\n");
else {printf("alloc3 success\n");free(p[0]);}
printf("end");
}
程序打印(使用 MSVC(带有调试和释放分配器)和 Win7 上的 MinGW 编译):
alloc failed for i=7896
Alloc1 after failed!
alloc2 success
alloc3 success
end
无论如何我可以避免这种情况吗?在我的实际应用程序中,我无法避免这种情况,我的程序达到了 2GB 内存限制......但我希望能够通过释放一些东西来继续。
为什么首先在这个小例子中会出现碎片?当我开始做“free-s”时,为什么没有压缩内存块,因为它们应该是相邻的。
谢谢!