目录
一、题目一
请问运行 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
,形参只是实参的一份临时拷贝,所以 Test 函数中的str
始终为 NULL。
修改:
void GetMemory(char** p)
{
*p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str);
if (NULL == str) // 对 malloc 函数的返回值做检查,避免对 NULL 指针解引用
{
return;
}
strcpy(str, "hello world");
printf(str);
free(str); // 手动释放动态开辟的内存空间,避免内存泄漏
str = NULL;
}
二、题目二
请问运行 Test 函数会有什么样的结果?
char* GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
GetMemory
函数返回的是字符数组p
中首元素的地址,而该数组是开辟在栈上,因此这是一个返回栈地址的问题。
修改:
char* GetMemory(void)
{
char* p = "hello world";
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
printf(str);
}
此时
GetMemory
函数返回的是字符串常量 "hello world" 中首个字符的地址,而字符串常量存储在常量区。
三、题目三
请问运行 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);
}
运行 Test 函数后,虽然会打印 hello,但问题在于,首先没有对
malloc
函数的返回值做检查,其次没有手动释放动态开辟的内存,可能导致内存泄漏。
修改:
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
if (NULL == str) // 对 malloc 函数的返回值做检查
{
return;
}
strcpy(str, "hello");
printf(str);
free(str); // 手动释放动态开辟的内存空间
str = NULL;
}
四、题目四
请问运行 Test 函数会有什么样的结果?
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
Test 函数的问题在于,首先没有对
malloc
函数的返回值做检查,其次错误地认为free
函数会修改str
的值,使其变为 NULL。
修改:
void Test(void)
{
char* str = (char*)malloc(100);
if (NULL == str)
{
return;
}
strcpy(str, "hello");
printf(str);
free(str);
str = NULL;
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}