首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

内存free 后还可strcpy?解决办法

2012-03-28 
内存free 后还可strcpy??#include stdio.h#include stdlib.h#include memory.h#include string.hv

内存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,测试代码如下:

C/C++ code
#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;} 

热点排行
Bad Request.