Does allocating using sizeof yield wrong size for structure pointers?

后端 未结 2 1633
一向
一向 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.

提交回复
热议问题