注册 登录
编程论坛 C++教室

[求助]内存分配问题

overcome 发布于 2007-11-15 14:19, 830 次点击

以下两个程序输出的结果为何不一样:请指点一二

程序1:
#include<iostream.h>
#include<string.h>
#include<malloc.h>
void main()
{
char *pstr;
pstr=(char *)malloc(100);
strcpy(pstr,"hello");
//cout<<pstr<<endl;
free(pstr);
if(pstr!=NULL)
{
strcpy(pstr,"world");
}

cout<<pstr<<endl;
}


程序2:
#include<iostream.h>
#include<string.h>
#include<malloc.h>
void main()
{
char *pstr;
pstr=(char *)malloc(100);
strcpy(pstr,"hello");
cout<<pstr<<endl;
free(pstr);
if(pstr!=NULL)
{
strcpy(pstr,"world");
}

cout<<pstr<<endl;
}

9 回复
#2
PcrazyC2007-11-15 15:07
觉得这种错误的程序还是不要讨论的好.
#3
overcome2007-11-18 09:56

why?

#4
overcome2007-11-18 09:58

我说的是最后一句输出语句

#5
aipb20072007-11-18 13:24
以下是引用PcrazyC在2007-11-15 15:07:48的发言:
觉得这种错误的程序还是不要讨论的好.

#6
zzj2332007-11-20 20:09
两个程序输出的结果不一样,是因为free(pstr);后pstr变成所谓的"野指针".
#7
cince2007-11-20 20:51





#8
zkkpkk2007-11-23 09:43
你为什么要free了他又把他的地址输出?
pstr是地址
*pstr是那个地址的值
#9
虫虫飞ya飞2007-11-23 11:39
呵呵
#10
我是杨过2007-11-24 12:00
强烈的看不明白楼主的意图!
1