前言
本文展示四道动态内存分配分配的经典笔试题,出自《高质量的C-C++编程》,作者林锐。
1,形参与实参
请问调用Test时会出现什么错误?
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
答:对形参p的修改不会影响str,str依然指向NULL,因访问空指针报错。且没有判断空间开辟是否成功,也没有及时地释放空间。
改正后
void GetMemory(char **p)
{
*p = (char *)malloc(100);
if(*p==NULL)
{
perror("worning");
}
}
void Test(void)
{
char *str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
free(str);
str=NULL;
}
2,栈区的销毁
请问调用Test时会出现什么错误?
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
答:虽然str确实指向‘h’的地址,但当函数GetMemory执行结束以后,其函数栈帧已被销毁,数组p内存的元素也已经返回操作系统,故不能达到目的。
3,被遗忘的free
请问运行Test后会发生什么?
void GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
答:忘记释放空间,导致内存泄漏。
改正后
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;
}
4,非法的访问
请问运行Test会有什么结果?
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
答:释放str后,空间已经回归操作系统,不可以再对其进行访问。且释放空间后应立刻将str赋为NULL。
感谢您的阅读与耐心~