先看例子1
#include <stdio.h>
void test()
{
char *tmp = (char*)malloc(100);
strcpy(tmp, "Hello");
free(tmp);
//try to access tmp
//由于并没有使用free的内存,所以内存中的数据并没有发生变化
if(tmp != NULL)
{
//strcpy(tmp, "world");
printf("%s", tmp);
}
return;
}
void main()
{
test();
return;
}
输出:Hello
在看例子2
#include <stdio.h>
void test()
{
char *tmp = (char*)malloc(100);
strcpy(tmp, "Hello");
free(tmp);
//try to access tmp
if(tmp != NULL)
{
strcpy(tmp, "world");
printf("%s", tmp);
}
return;
}
void main()
{
test();
return;
}
//所以情况是这样的,free后,内存并没有为空,还保存有原来的数据。
//而内存若被从新分配后,tmp会指向“垃圾内存”,而成为野指针。
输出:World
#include <stdio.h>
void test()
{
char *tmp = (char*)malloc(100);
strcpy(tmp, "Hello");
free(tmp);
char *tmp1 = (char*)malloc(150);
strcpy(tmp1, "new memory");
if(tmp != NULL)
{
//strcpy(tmp, "world");
printf("%s\n", tmp);
strcpy(tmp, "use tmp not tmp1");
printf("%s\n", tmp);
}
return;
}
void main()
{
test();
return;
}
输出:Hello
use tmp not tmp1