内存free 后还可strcpy??
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
void main()
{
char *str= (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL){
strcpy(str, "world");
printf(str);
}
}
打印结果:world
str地址处的内存不是已经被free了吗?为什么还可以存放world ????
[解决办法]
我的运行结果第一次就崩溃了.因为释放后str并不指向空,if(str != NULL)为真.
就是野指针.你的程序不崩溃是偶然情况.
一般释放后都这样保证安全:str=NULL;
[解决办法]
在我的编译器上可以,MinGW Studio 2.05,测试代码如下:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){ char* ptr = (char*)malloc(sizeof(char)*10); strcpy(ptr, "hello"); printf("%s\n", ptr); free(ptr); strcpy(ptr, "world"); printf("%s\n", ptr); return 0;}