目录
在学习了关于动态开辟内存的相关知识后,下面是一些涉及到动态开辟内存程序的试题及解析(试题部分来自《高质量的C/C++编程》、笔试题)。
第1题
分析下面这段代码,为什么运行错误?

代码
cpp
void GetMemory(char* p)
{
p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello,world");
printf(str);
}
int main()
{
Test();
return 0;
}
解答分析:
1.对NULL指针进行了解引用操作,程序会崩溃
2.没有释放空间,内存泄漏的问题
3.str为指针变量,传递到函数中,只是拷贝了一份也就是p,形参p的改变不影响str,p指向的malloc开辟的空间会在函数外被收回。

以下是改进后的程序👇

第2题
分析下面这段代码,运行结果为什么是乱码?

代码
cpp
char* GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
}
解答分析:
p被返回时,p指向的空间同时因为出函数而被系统收回,所以str被赋予野指针,用printf打印str所指空间属于非法访问。

第3题
分析下面两段代码,为什么结果大不相同??

代码
cpp
int* test()
{
int a = 10;
return &a;
}
int main()
{
int* p=test();
printf("hehe");
printf("%d\n", *p);
return 0;
}
解答分析:
从函数栈帧角度分析,test开辟的函数栈帧收回后,没有被系统及时利用,就有可能被指针访问到之前的内容,之后被printf重新利用后,原有内容被覆盖。👇

第4题
下面这段程序有什么错误?

代码
cpp
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
解答分析:
这段程序能够运行成功,唯一错误的地方就是malloc在开辟内存空间后,没有用free释放这段空间。容易造成内存泄漏。
用free正确释放malloc开辟的空间👇

第5题
为什么下面这段程序运行结果为乱码??

代码
cpp
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
str = NULL;
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
解答分析:
str所指的空间被free释放后,空间交换给系统,str变为野指针,属于非法访问。
在free释放str所指向空间后应该及时str=NULL置空,且不能在访问。
