#include<stdio.h>
#include <malloc.h>
main()
{
char *buf=NULL;
buf = (char*)malloc(1024*1024);
buf = (char*)malloc(1024*1024);
buf = (char*)malloc(1024*1024);
buf = (char*)malloc(1024*1024);
buf = (char*)malloc(1024*1024);
buf = (char*)malloc(1024*1024);
buf = (char*)malloc(1024*1024);
buf = (char*)malloc(1024*1024);
}
上面一段代码内存只涨了1M;VC6,直接写了个C文件运行的;其他人测试vs2005说涨了8M;
#include<stdio.h>
#include <malloc.h>
main()
{
char *buf=NULL;
buf = (char*)malloc(1024*1024);
if (buf!=NULL)
{
printf("%ld/n",buf);
}
buf = (char*)malloc(1024*1024);
if (buf!=NULL)
{
printf("%ld/n",buf);
}
buf = (char*)malloc(1024*1024);
if (buf!=NULL)
{
printf("%ld/n",buf);
}
}
运行结果:
4390976
5505088
6619200
上面代码每次分配的地址都不一样
#include<stdio.h>
#include <malloc.h>
main()
{
char *buf=NULL;
buf = (char*)malloc(1024*1024);
if (buf!=NULL)
{
printf("%ld/n",buf);
printf("%ld/n",strlen(buf));
}
free(buf);
buf = (char*)malloc(1024);
if (buf!=NULL)
{
printf("%ld/n",buf);
printf("%ld/n",strlen(buf));
}
free(buf);
}
运行结果:
4390976
1048580
3682560
1028
strlen的结果都刚好比分配的长度多了4,不由得想起一篇讨论“生死疆界”的文章;
#include<stdio.h>
#include <malloc.h>
main()
{
char *buf=NULL;
buf = (char*)malloc(1024*1024);
if (buf!=NULL)
{
printf("%ld/n",buf);
printf("%ld/n",strlen(buf));
}
free(buf);
buf = (char*)malloc(10);
if (buf!=NULL)
{
printf("%ld/n",buf);
printf("%ld/n",strlen(buf));
}
memset(buf,0x00,strlen(buf));
free(buf);
}
上面多加了一句memset,程序就出现了异常,这让我更相信“生死疆界”中提出的一个关于界限的问题CF;
#include<stdio.h>
#include <malloc.h>
main()
{
char *buf=NULL;
buf = (char*)malloc(1024*1024);
if (buf!=NULL)
{
printf("%ld/n",buf);
printf("%ld/n",strlen(buf));
}
free(buf);
buf = (char*)realloc(buf,10);
if (buf!=NULL)
{
printf("%ld/n",buf);
printf("%ld/n",strlen(buf));
}
memset(buf,0x00,strlen(buf));
free(buf);
}
上面这段代码跑玩第一个free后就程序出现异常,realloc有问题;
注释第一个free,程序能执行,但老提示遇到问题需关闭;
注释memset(buf,0x00,strlen(buf));问题依旧;
然后注释第二个memset(buf,0x00,strlen(buf));程序正常;
所以问题应该是malloc的时候确实存在多分配,有带标识尾:4个CF;
因此strlen的使用有问题;
但是为什么第一个strlen的存在没有引起报错????