使用sizeof分配是否会为结构指针产生错误的大小?

Pes*_*udo 0 c malloc pointers

使用valgrind读取此消息,我得到:大小为4的无效写入/读取

 struct Person{
        char* name;
        int age;
    };

    struct Person* create_person(char *name, int age)
    {
        struct Person* me = (struct Person*)malloc(sizeof(struct Person*));
        assert(me!= NULL); //make sure that the statement is not null
        me->name = name;
        me->age = age;

        return me;
    }
Run Code Online (Sandbox Code Playgroud)

使用此得到的干净日志与valgrind

struct Person{
    char* name;
    int age;
};

struct Person* create_person(char *name, int age)
{
    struct Person* me = (struct Person*)malloc(sizeof(struct Person*)+4);
    assert(me!= NULL); //make sure that the statement is not null
    me->name = name;
    me->age = age;

    return me;
}
Run Code Online (Sandbox Code Playgroud)

我为什么要明确指出sizeof(struct+intSize)要避免此错误?sizeof没有得到结构的整个大小?

R S*_*ahu 5

您对的调用使用了错误的大小malloc

struct Person* me = (struct Person*)malloc(sizeof(struct Person*));
                                                  ^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

那是指针的大小,而不是对象的大小。您需要使用:

struct Person* me = (struct Person*)malloc(sizeof(struct Person));
Run Code Online (Sandbox Code Playgroud)

为避免此类错误,请使用以下模式,并且不要强制转换的返回值malloc(请参阅是否强制转换malloc的结果?):

struct Person* me = malloc(sizeof(*me));
Run Code Online (Sandbox Code Playgroud)

这是一个巧合malloc(sizeof(struct Person*)+4)。您struct有一个指针和一个int。它sizeof(int)在您的平台上显示为4。因此,sizeof(struct Person*)+4恰好匹配的大小struct Person