现象:下述代码中的指针p是不能被free的,否则会报错!
原因:动态分配之后,p指向的是堆区的地址;之后又在代码中又将p指向了栈区中的地址,此时,此p非彼p。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct MyStruct
{
char name[20];
int age;
}MyStruct;
int main()
{
MyStruct t1={"Tom",12 };
//MyStruct t1;
MyStruct *p = (MyStruct *)malloc(sizeof(MyStruct));
if (p == NULL)
return -1;
printf("&p=%u\n", p);
p = &t1;
(*p).age = 155;
printf("&p=%u\n", p);
//fun(buf);
printf("%s\t%d\n", p->name, t1.age);
//if (p != NULL)
//{
// free(p);
// p = NULL;
//}
printf("Hello, World! \n");
system("pause");
return 0;
}