首页 > 解决方案 > 访问动态分配的 C 结构数组时出现段错误

问题描述

我有以下以下列方式定义的结构

typedef struct _abcd {
    int a;
    unsigned long b;  
    void (*c)(int);
    int d;
} abcd_t, *abcd;

现在我有以下代码

static abcd foo

int set_size(int size){
   foo = malloc(sizeof(abcd) * size);
}

由于某种原因,此代码在访问数组成员的某些属性时给了我段错误。但我注意到,如果我将 malloc 行更改为以下内容 - 它可以解决问题

foo = malloc(sizeof(foo[0]) * size);

我觉得很奇怪很明显sizeof(foo[0]) = sizeof(abcd) 那么这里到底有什么区别?

谢谢

标签: cmallocdynamic-arrays

解决方案


obviously sizeof(foo[0]) = sizeof(abcd)

It is not the same since you typedefed abcd to be a *pointer* to struct _abcd.

Use

foo = malloc(sizeof(*foo) * size);

to have robust code even if the type of foo should change at some point.

Your

foo = malloc(sizeof(foo[0]) * size);

is essentially the same since foo[0] is just syntactic sugar for *(foo + 0) which becomes *foo.


推荐阅读