版本信息:
gcc 版本 6.4.1 20170727 (Red Hat 6.4.1-1) (GCC)
先来看下现象:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char *buff = (char *)malloc(10);
memcpy(buff, "test", 10);
printf("buff = %s, buff self address = %x, buff point address = %x\n", buff, &buff, buff);
free(buff);
printf("buff = %s, buff self address = %x, buff point address = %x\n", buff, &buff, buff);
return 0;
}
$ gcc malloc.c
$ ./a.out
buff = test, buff self address = f2efa428, buff point address = 14b3010
buff = , buff self address = f2efa428, buff point address = 14b3010
分析:
- free后,buff指向的内存中内容清空,buff任然存储了这块内存的地址
是否还可以读写free后的内存块呢?继续测试:
int main()
{
char *buff = (char *)malloc(10);
memcpy(buff, "test", 10);
printf("buff = %s, buff self address = %x, buff point address = %x\n", buff, &buff, buff);
free(buff);
printf("buff = %s, buff self address = %x, buff point address = %x\n", buff, &buff, buff);
//读写free后的内存块
*buff