0

Using valgrind to read this I get: Invalid write/read of size 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;
    }

Using this got clean log with 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;
}

Why should I explicitly put sizeof(struct+intSize) to avoid this error? sizeof don't get the whole size of a struct?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
aracyla
  • 58
  • 8

2 Answers2

5

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.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

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.

user253751
  • 57,427
  • 7
  • 48
  • 90