(经典C++面试题)指针、双指针、内存分配

来源:互联网 发布:灯光编程教学视频 编辑:程序博客网 时间:2024/05/01 13:58
下面题目来自CSDN
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");将使程序崩溃。

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


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)内存泄漏
//-------------------------------------------------
//转载请注明出处:http://mxmkeep.blog.163.com/blog/static/10649241520103511210810/
下面是我自己的理解:
(1)、char *str = NULL;//指针str上的值为NULL,
GetMemory(str);//str将自己的值赋给p,此时p的值为NULL
进入GetMemory函数,
p=(char*)malloc(100);//申请动态内存空间,并将内存基地址的值(假设为S)赋给p此时,p的值为s。
但GetMemory函数所进行的一切,都与str无关,p只是拷贝了str的值。
所以str的值还是NULL,因此,对str进行赋值,将会使程序崩溃

(2)、char p[]="helloworld";
return p;
//"helloworld"在栈内存中,p指向此栈内存基地址,但函数运行结束后,此内存将被释放。
str = GetMemory();//str指向一片已被释放的空间,其值不可知

(3)、GetMemory(&str, 100);//将str的地址赋给p,而不是值。此时*p为str的值
*p = (char*)malloc(num);//更改str的值,即更改str指向的内存空间
因此,str能打印出"hello"