题目1:
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
请问运行Test函数会有什么结果
答:运行Test函数首先创建并赋值 字符str指针。然后进入Get函数,在内部动态开辟100个字节的内存空间,地址存放在p处,但是出了函数之后p就销毁了。以上这些跟str都没有什么关系,str仍然还是一个空指针,所以后面的strcpy函数也就无法copy了,所以什么也不打印。
题目2:
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
问:请问运行Test函数会有什么问题?
答:创建并赋值字符空指针str,随后调用Get函数得到字符数组p的地址,这个没有任何问题,但是当出了Get函数之后,字符数组p就被销毁了,也就是说str指向了一个未知内容的空间。
题目3:
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函数会有什么问题?
答:这里创建二级指针变量,把str的地址传过去了,然后再Get函数中malloc开辟100个字节的空间,整体来说没有太大的问题,也能够打印hello,但是唯一的缺点就是没有释放str,会产生内存泄漏的问题。
题目4:
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
if (str != NULL)
{
strcpy(str, "world");
//str = "world";
printf("%s\n",str);
printf("%s\n", str);
}
}
int main()
{
Test();
return 0;
}
问:程序运行有什么问题?
答:程序运行之后能够打印world,唯一的问题就是非法使用空间,str所指向的空间已经被free函数释放,但是str依旧指向那块空间,所以strcpy依旧能执行,只不过是非法使用空间。