指针作为参数的申请内存函数

如果函数的参数是一个指针,不要指望用该指针去申请动态内存。

示例程序1:

void GetMemory(char *p, int num)
{
    p = (char *)malloc(sizeof(char) * num);
}

void Test(void)
{
    char *str = NULL;
    GetMemory(str, 100); // str 仍然为 NULL
    strcpy(str, "hello"); // 运行错误
}
//每执行一次都会内存泄漏

对于传入的指针参数 p 来说,编译器会为该参数创建一个临时副本,例如 _p。函数体中只是修改了形参_p的内容,对于实参p没有任何影响,想要对指针参数进行修改,要传递指针的指针,即二级指针。

正确的代码如下:

void GetMemory2(char **p, int num)
{
    *p = (char *)malloc(sizeof(char) * num);
}

void Test2(void)
{
    char *str = NULL;

    GetMemory2(&str, 100); // 注意参数是 &str,而不是 str
    strcpy(str, "hello");

    free(str);
}

猜你喜欢

转载自blog.csdn.net/Zhoujy1996/article/details/81170318