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

时间:2016-02-02 03:27:01

标签: c pointers malloc

使用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;
    }

使用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;
}

为什么我应该明确地sizeof(struct+intSize)来避免这个错误? sizeof没有获得结构的整个大小?

2 个答案:

答案 0 :(得分:5)

您在malloc的调用中使用了错误的尺寸。

struct Person* me = (struct Person*)malloc(sizeof(struct Person*));
                                                  ^^^^^^^^^^^^^^^

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

struct Person* me = (struct Person*)malloc(sizeof(struct Person));

为了避免这样的错误,请使用以下模式,不要转换malloc的返回值(请参阅Do I cast the result of malloc?):

struct Person* me = malloc(sizeof(*me));

malloc(sizeof(struct Person*)+4)的作用很巧合。您的struct有一个指针和int。您平台上的sizeof(int)似乎是4.因此,sizeof(struct Person*)+4恰好与struct Person的大小匹配。

答案 1 :(得分:1)

因为你想分配足够的空间来容纳整个结构,而不仅仅是指向它的指针。

即,使用sizeof(struct Person)而非sizeof(struct Person*)

sizeof(struct Person*)+4 巧合在你的平台上足够大。

相关问题