Using valgrind to read this I get: Invalid write/read of size 4
struct Person{
char* name;
int age;
};
struct Person* create_pers
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
.
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.