Does allocating using sizeof yield wrong size for structure pointers?

后端 未结 2 1632
一向
一向 2020-12-22 08:38

Using valgrind to read this I get: Invalid write/read of size 4

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

    struct Person* create_pers         


        
2条回答
  •  星月不相逢
    2020-12-22 09:03

    Because you want to allocate enough space to hold an entire structure, not just a pointer to it.

    That is, use sizeof(struct Person) and not sizeof(struct Person*).

    sizeof(struct Person*)+4 is coincidentally big enough on your platform.

提交回复
热议问题