C - freeing structs

2019-01-10 07:30发布

Let's say I have this struct

typedef struct person{
    char firstName[100], surName[51]
} PERSON;

and I am allocating space by malloc and filling it with some values

PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));
strcpy(testPerson->firstName, "Jack");
strcpy(testPerson->surName, "Daniels");

What is the correct and safe way to free all memory taken by that struct? Is "free(testPerson);" enough or do I need to free each struct's attribute one by one?

It leads me to another question - how are structures stored in memory? I noticed a strange behaviour - when I try to print structure address it's equal to it's first attribute's address.

printf("Structure address %d == firstName address %d", testPerson, testPerson->firstName);

Which means that this free(testPerson) should be equal to this free(testPerson->firstName);

and that's not what I want to do.

Thanks

标签: c struct malloc
7条回答
我命由我不由天
2楼-- · 2019-01-10 08:20

Because you defined the struct as consisting of char arrays, the two strings are the structure and freeing the struct is sufficient, nor is there a way to free the struct but keep the arrays. For that case you would want to do something like struct { char *firstName, *lastName; }, but then you need to allocate memory for the names separately and handle the question of when to free that memory.

Aside: Is there a reason you want to keep the names after the struct has been freed?

查看更多
登录 后发表回答