【问题标题】:Why this failed when I use a function to malloc memory [duplicate]为什么当我使用函数分配内存时失败了[重复]
【发布时间】:2015-09-21 06:43:18
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

char** mlc(char** f){
    int count=10;
    int size=10;
    f=(char**)malloc(count*sizeof(char*));
    for(int i=0;i<count;i++){
        f[i]=(char*)malloc(size*sizeof(char));
    }
    return f;
}
int main()
{
    char** f;
    f=mlc(f);
    f[0][0]='1';
    f[0][1]='\0';
    printf("%s",f[0]);
    return 0;
}

我使用这段代码可以完美运行,但是当我使用下面的代码时,会出现分段错误:

#include <stdio.h>
#include <stdlib.h>

void mlc(char** f){
    int count=10;
    int size=10;
    f=(char**)malloc(count*sizeof(char*));
    for(int i=0;i<count;i++){
        f[i]=(char*)malloc(size*sizeof(char));
    }
    return f;
}
int main()
{
    char** f;
    mlc(f);
    f[0][0]='1';
    f[0][1]='\0';
    printf("%s",f[0]);
    return 0;
}

所以,主要区别是第一个代码我返回了指针,为什么第二个代码出错了?

【问题讨论】:

  • see why not to castmalloc()C中的family返回值。
  • @SouravGhosh 你是 no-casting-malloc 的 Barry Allen :p
  • "...第一个代码我返回了指针,为什么第二个代码出错了?因为你做了not"return [修改] 指针".
  • so(因为答案被阻止),这可能是不好的编程风格,但是将void 更改为void* 并将mlc(f); 行更改为f=mlc(f); 可以解决您的问题(如@SouravGhosh指出,您没有将f 分配回来)。
  • 需要注意的几个关键事项:1) 在这两个示例中,发布的代码都无法干净地编译。建议在编译和修复这些警告时启用所有警告。 2) 'sizeof(char)' 始终为 1,因此对 malloc() 的调用没有影响。 IE。它只是使代码混乱。建议删除该表达式。 3) 总是检查 (!=NULL) malloc() 的返回值以确保操作成功 4) 编译器抱怨未初始化的参数给 mlc()。建议去掉那个参数,在mlc函数本地定义'f',

标签: c pointers segmentation-fault malloc dynamic-memory-allocation


【解决方案1】:

C 中,函数参数按值传递。因此,在函数内部,您不能更改参数的值并期望更改会反映到调用者传入的变量上。

简单来说,在您的情况下,从mlc() 内部,您可以更改*f 的值,这将反映到main() 中的*f,但您不能更改 f 本身的值

  • 您的第一个案例有效,因为在分配内存并将 参数 f 指向它之后,您 return 表示指针并将其检索到 main() 中的 f。所以,在main() 中,f 完全可以使用。

  • 您的第二种情况失败,因为从函数返回后,main() 中的f 仍未初始化。

【讨论】:

  • @Quentin 感谢您的修复。我应该自己注意到并做到这一点。下次我会小心的。
猜你喜欢
  • 2012-06-02
  • 2021-01-10
  • 2020-09-02
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2018-08-24
相关资源
最近更新 更多