Does allocating using sizeof yield wrong size for structure pointers?

后端 未结 2 1608
一向
一向 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 08:55

    You are using the wrong size in the call to malloc.

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

    That is a size of a pointer, not the size of an object. You need to use:

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

    To avoid errors like this, use the following pattern and don't cast the return value of malloc (See Do I cast the result of malloc?):

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

    It's a coincidence that malloc(sizeof(struct Person*)+4) works. Your struct has a pointer and an int. It appears sizeof(int) on your platform is 4. Hence, sizeof(struct Person*)+4 happen to match the size of struct Person.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题