一、内存的思考题。请问运行Test函数会有什么样的结果?
第一题:
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf("%s", str);
}
结果:![在这里插入图片描述](https://img-blog.csdnimg.cn/4300c898f8dc4485a57bf33e672ff6e7.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5qCR5LiL562J6Iu55p6c,size_20,color_FFFFFF,t_70,g_se,x_16)
在语句strcpy(str, "hello world")
发生错误。引发的异常: 0xC0000005
: 写入位置 0x00000000
时发生访问冲突。
分析: 由异常可知,strcpy
函数试图将“hello world”
写入位置0x00000000
出错,这个位置是通过char *str = NULL
语句,将str
指向0x00000000
。但我们后面又试图通过GetMemory(str)
,使用malloc()
为str分配大小为100字节的动态空间。但通过结果来看,str
的指向没有改变,即现在str指针指向的空间大小为0,而strcpy(str, "hello world")
试图将12个字节的hello world
写入空间大小为0的内存中,所以出错。
进一步分析错误原因: 我们在GetMemory()
函数添加语句:printf("p 指向的首地址 %p", p);
void GetMemory(char* p)
{
p = (char*)malloc(100);
printf("p 指向的首地址 %p", p); //查看p申请到的动态空间的首地址
}
void Test(void)
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf("%s", str);
}
输出结果:
p 指向的首地址 00CF4B48
有结果我们可知,哪里malloc
确实为p申请了一块空间。那为什么str
还指向NULL
呢?原因是实参与形参之间的值传递是单向的只能由实参传给形参(即str->p),而不能由形参传给实参(p->str)。
要修改该程序很简单,既然p已经申请到了一块空间,我们只需要使用p即可,但p是局部变量,GetMemory(char* p)
结束后,p也被释放了。那么我们只需在GetMemory(char* p)
中返回p就好了。
修改后的程序如下::
char * GetMemory(char* p)
{
p = (char*)malloc(100);
return p;
}
void Test(void)
{
char *str=NULL;
str=GetMemory(str);
strcpy(str, "hello world");
printf("%s", str);
}
输出:hello world
第二题:
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf("%s", str);
}
运行结果:烫烫烫烫烫烫庚?
结果出现了乱码。
分析:
“hello world”这个字符串在GetMemory函数中定义的,函数执行结束后该字符串的空间会被释放,该函数传回该字符串的首地址,但在main函数,该首地址已经不指向“hello world”这个字符串,所以str即使得到了原来存放该字符串的地址首地址,但已经无法指向该字符串,因为它已经被释放(删除)了。