简体   繁体   English

为什么访问 malloced 结构数组的成员会出现段错误?

[英]Why does accessing a member of a malloced array of structs seg fault?

I am working through Learn C The Hard Way and am stumped on something.我正在学习 Learn C The Hard Way,但遇到了一些困难。 I've written a simplified version of the problem I am running into to make it easier to get down to it:我已经编写了我遇到的问题的简化版本,以便更容易解决它:

#include <stdlib.h>

#define GROUP_SIZE 10
#define DATA_SIZE 64

struct Dummy {
    char *name;
};

struct Group {
    struct Dummy **dummies;
};

int main() {
    struct Group *group1 = malloc(sizeof(struct Group));
    group1->dummies = malloc(sizeof(struct Dummy) * GROUP_SIZE);
    struct Dummy *dummy1 = group1->dummies[3];

    // Why does this seg fault?
    dummy1->name = (char *) malloc(DATA_SIZE);

    return 0;
}

When I try to set the name pointer on one of my dummies I get a seg fault.当我尝试在我的一个假人上设置名称指针时,出现段错误。 Using valgrind it tells me this is uninitialized space.使用 valgrind 它告诉我这是未初始化的空间。 Why is this?为什么是这样?

Your use of dummies appears inconsistent with its declaration .您对dummies使用似乎与其声明不一致。 From the way you use the dummies field it appears that dummies was intended as an array of Dummy structs, not an array of arrays of Dummy structs.从您使用dummies字段的方式来看, dummies似乎旨在作为Dummy结构的数组,而不是arrays Dummy结构的数组。 If this is the case, change your declaration to this:如果是这种情况,请将您的声明更改为:

struct Group {
    struct Dummy *dummies; // Single asterisk
};

Then change your usage as follows:然后按如下方式更改您的用法:

struct Dummy *dummy1 = &group1->dummies[3];

Of course this assumes that GROUP_SIZE is four or more.当然,这假设GROUP_SIZE为四或更多。

you never malloced space for the Dummy itself.你从来没有为Dummy本身分配空间。 You need to do something like:您需要执行以下操作:

group1->dummies = malloc(sizeof(Dummy *) * GROUP_SIZE);
for(int i = 0; i < GROUP_SIZE; i++) {
   group1->dummies[i] = malloc(sizeof(struct Dummy));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM