c++中关于内存的一些问题

来源:互联网 发布:工程造价定额查询软件 编辑:程序博客网 时间:2024/06/06 20:26

原帖地址:http://topic.csdn.net/u/20100318/21/ae111d42-27e4-413a-9fd9-7132367d9f91.html

 

void GetMemory(char *p)
{
p=(char*)malloc(100);
}

void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str,"helloworld");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:程序崩溃。因为GetMemory并不能传递动态内存,Test函数中的str一直都是NULL。strcpy(str,"helloworld");将使程序崩溃。
解析:该函数中的p是一个临时的指针变量,与调用GetMemory函数的实参不是同一个变量,所以无法返回申请的内存。可以做如下改进 void GetMemory(char* &p);


char *GetMemory(void)
{
char p[]="helloworld";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
请问运行Test函数会有什么样的结果?
答:可能是乱码。因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是NULL,但其原先的内容已经被清除,新内容不可知。
解析:p是局部变量,在离开作用域后栈空间会被回收,结果不可预料。


void GetMemory2(char **p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
请问运行Test函数会有什么样的结果?
答:(1)能够输出hello(2)内存泄漏

解析:p是指向传入的指针的指针,*p为传入的指针赋值,所以改变了传入指针的值,也可以写成这样:
void GetMemory(char *&p)
{
p=(char*)malloc(100);
}
效果一样

原创粉丝点击