1

我创建了一个结构数组 Human ,其中包含char *name.

我使用这样的功能:

Human *createHuman(char *name){
    Human *h = malloc(sizeof(Human));
    h->name = strdup(name);
    return h;
}

我已经测试了这个功能,它工作得很好,但是当我像这样使用它时我的问题就开始了:

void gen_Humans(Human array[MAX], int n){
    //n == max;
    for (int i = 0; i<n; i++){
        char *name = gen_name_function_used_before_WORKING();
        array[i] = *createHuman(*name);
    }
    …
}

正如我所说,如果我生成一个人类,它就可以正常工作。我调试了我的代码,当我谈到strdup(name)它的时候,我抛出了这个:

my error: Exception thrown at 0x53DCF6E0 (ucrtbased.dll) in project.exe:
0xC0000005: Access violation reading location 0x00000070.

我正在使用 VS 2017 企业版。

4

2 回答 2

1

当调用你的函数时createHuman,你传递的是你的名字的值:

array[i] = *createHuman(*name);

构建此应用程序时,我收到以下编译器警告 (GCC):

warning: passing argument 1 of 'createHuman' makes pointer from integer without a cast

由于您的函数createHuman需要名称的地址,因此您还应该传递地址。例如:

array[i] = *createHuman(name);
于 2019-04-15T16:55:52.730 回答
1

添加到@MortizSchmidt 的答案:

  • 您没有检查malloc(). 即使失败的可能性很小,您也应该这样做。
  • 您正在泄漏内存 - 因为您从未释放malloc()ed 内存,也没有将指针保存在任何地方。请记住 C 不像 Java - 赋值不是引用的赋值。
  • 请注意,MAX函数签名中的指示符没有任何作用。该参数是一个 int* ,无论您如何编写它int* arrayint array[]int array[MAX].

实际上,为什么还要分配 Human 结构而不仅仅是为字符串分配空间?

struct Human createHuman(char *name){
    if (name == NULL) {
        struct Human h = { NULL };
        return h;
    }
    struct Human h = { strdup(name) };
    if (h.name == NULL) { /* handle error here */ }
    return h;
}

void gen_Humans(Human array[MAX], int n){
    for (int i = 0; i < n; i++) {
        char *name = gen_name_function_used_before_WORKING();
        array[i] = createHuman(name);
    }
    …
}

Human这具有将after中的所有字段初始化name为 0的额外好处。

于 2019-04-15T17:11:44.683 回答