//运行Test()会有怎样的结果
#include<iostream>
#include<cstring>
using namespace std;
char *GetMemory(void)
{
char p[] = "hello world";//局部变量,运行后会自动销毁
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
int main()
{
Test();//返回结果可能是乱码,p是一个数组,内存分配在栈上,GetMemory返回的是指向“栈内存”的指针,指针的地址不是NULL,但是内容被清除
}
/*
//修改如下
//1
char *GetMemory(void)
{
static char p[] = "hello world";//数组位于静态存储区,可以通过函数返回
return p;
}
//2
char *GetMemory(void)
{
char *p = "hello world";//p是指向全局(静态)存储区的指针,可以通过函数返回
return p;
}
//3
char *GetMemory(void)
{
char *p = (char*)malloc(12);//p是指向堆中分配存储空间的指针,可以通过函数返回,但是需要调用free释放内存,否则造成内存泄漏
if(p==NULL)
return NULL;
else
p="hello world";
// strcpy(p,"hello world");也可以
return p;
}*/确保不是在栈区申请内存
最新推荐文章于 2024-11-21 10:10:51 发布
2710

被折叠的 条评论
为什么被折叠?



