我写了下面这个玩具程序,观察到第二个变量test2将会占用第一个变量test1释放的内存地址。即使我使用free(test1)释放了test1的内存,test2仍将保留test1的字段值。我想知道如何在C语言中清除free()留下的数据:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct test_str
{
char name[128];
int Id;
} test_str;
typedef test_str* mytest;
int main()
{
mytest test1 = malloc(sizeof(test_str));
printf("test1 pointer address is %p \n", test1);
strcpy(test1->name, "hello world");
test1->Id = 10;
free(test1);
// test1->name = NULL; /* this does not work */
// test1->Id = 0; /* without resetting Id = 0, test2->Id will show 10 */
test1 = NULL;
mytest test2 = malloc(sizeof(test_str));
printf("test2 pointer address is %p, name field is %s, Id = %d \n", test2, test2->name, test2->Id);
return 0;
}
这是输出结果:
test1指针地址为0x2401010
test2指针地址为0x2401010,名称字段为hello world,ID = 10
memset
。 - Linuxios