对NULL指针进行解引用引发的问题
先看一段代码
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
这段代码有什么问题?使用C-Free运行后发现,hello world无法打印。
1、首先是malloc后没有free的问题,不过这个问题不影响helloworld的打印。
2、问题原因,因为函数外定义str = NULL,而传参是定义了一个指针变量*p,该变量在函数运行完就被销毁了,又因为GetMemory中是没有返回值的,那么运行完GetMemory后,str还是指向的NULL。为了验证这一点,做了个小实验用以证实:
对于这个问题,我们有三种解决办法。
1、GetMemory内加一个返回值,str用来接收这个返回值,使其不为NULL
#include "stdio.h"
#include "stdlib.h"
char *GetMemory(char *p)
{
p = (char *)malloc(100);
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory(str);
strcpy(str, "hello world");
printf(str);
free(str);
}
int main(void)
{
Test();
return 0;
}
2、去掉str = NULL的初始化
#include "stdio.h"
#include "stdlib.h"
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
free(str);
}
int main(void)
{
Test();
return 0;
}
3、传递二级指针
#include "stdio.h"
#include "stdlib.h"
void GetMemory(char **p)
{
*p = (char *)malloc(100);
}
void Test(void)
{
char *str=NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
free(str);
}
int main(void)
{
Test();
return 0;
}
至于第二点为什么能成功?可能刚好碰巧str指向和函数GetMemory内p指针指向的是同一块内存?大家有知道原因的可以留言告诉我,我个人觉得第二点不是很严谨,还是第三点解决方法最好。
后续:试了一下,没有给str分配空间,也能strcpy,str和p指向的并不是同一块内存。这里应该是C-free编译器出问题了,所以能解释第二点为什么能成功。