[英]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.