小编Pes*_*udo的帖子

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

使用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 …
Run Code Online (Sandbox Code Playgroud)

c malloc pointers

0
推荐指数
1
解决办法
99
查看次数

标签 统计

c ×1

malloc ×1

pointers ×1