C - freeing structs

133,348

Solution 1

Simple answer : free(testPerson) is enough .

Remember you can use free() only when you have allocated memory using malloc, calloc or realloc.

In your case you have only malloced memory for testPerson so freeing that is sufficient.

If you have used char * firstname , *last surName then in that case to store name you must have allocated the memory and that's why you had to free each member individually.

Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free() it first then free the pointer to object.

Freeing each element you can see the demo shown below:

typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->firstname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName

.
. // do whatever you want

free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);

The reason behind this is, if you free the ptrobj first, then there will be memory leaked which is the memory allocated by firstname and suName pointers.

Solution 2

First you should know, how much memory is allocated when you define and allocate memory in below case.

   typedef struct person{
       char firstName[100], surName[51]
  } PERSON;
  PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));

1) The sizeof(PERSON) now returns 151 bytes (Doesn't include padding)

2) The memory of 151 bytes is allocated in heap.

3) To free, call free(testPerson).

but If you declare your structure as

  typedef struct person{
      char *firstName, *surName;
  } PERSON;
  PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));

then

1) The sizeof(PERSON) now returns 8 bytes (Doesn't include padding)

2) Need to allocate memory for firstName and surName by calling malloc() or calloc(). like

        testPerson->firstName = (char *)malloc(100);

3) To free, first free the members in the struct than free the struct. i.e, free(testPerson->firstName); free(testPerson->surName); free(testPerson);

Solution 3

free is not enough, free just marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULL after free.

Ex:

if (testPerson) {
    free(testPerson);
    testPerson = NULL;
}

struct is similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0 so the address of first struct's member is same as the address of struct.

Solution 4

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?

Solution 5

This way you only need to free the structure because the fields are arrays with static sizes which will be allocated as part of the structure. This is also the reason that the addresses you see match: the array is the first thing in that structure. If you declared the fields as char * you would have to manually malloc and free them as well.

Share:
133,348
user10099
Author by

user10099

Updated on July 23, 2022

Comments

  • user10099
    user10099 almost 2 years

    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

  • user10099
    user10099 over 11 years
    I dont want to keep nothing and that's the thing :) After freeing it (using free(testPerson)), I was still able to access it's surName by testPerson->surName and it returned right value, but I was not able to access it's first attribute (firstName), it gave me some random chars. That's why I was worried if free(testPerson) was enough
  • Niklas R
    Niklas R over 11 years
    Also, Variables are usually not allocated on the heap, that's why free(&x) might already fail.
  • Niklas R
    Niklas R over 11 years
    I think the free(testPerson->firstName) is confusing to beginners, regarding to why it works.
  • user10099
    user10099 over 11 years
    Well I understand it now, I was just worried that the other struct attributes were stucked in memory. Thanks
  • MK.
    MK. over 11 years
    I'm tempted to downvote for really careless use of language but won't as to not discourage a new user from posting. However there are 2 glaring mistakes that need to be pointed out: it is not clear what you mean by "arrays are represented by pointers" and it is not clear what "valid code" means. int x; free(&x); is not valid code.
  • user10099
    user10099 over 11 years
    Thanks. So I only need to take care of the dynamic variables, as in functions
  • Undeterminant
    Undeterminant over 11 years
    @MK.: Thank you for pointing out these mistakes; I was trying to figure out how to properly word it because I wanted to make sure that I wasn't using language which applies to C++ and not C. It's much clearer, now.
  • dmckee --- ex-moderator kitten
    dmckee --- ex-moderator kitten over 11 years
    @user10099 free only alters some data in the parts of memory that the alloc family of functions use for bookkeeping, which means that the characters making up your strings stay in memory until they are overwritten, but one you have called free (1) it is formally incorrect to access that memory again (unless a later allocation reuses it) and (2) you don't have any guarantee of what is there.
  • djna
    djna over 11 years
    As I said clear code would use free(testPerson). However there's no avoiding the fact that the other call will actually work, that's how the memory model works. At some time you have to understand pointers.
  • Shash
    Shash over 11 years
    For the last sentence, memory leak is probably because of structure padding.
  • Omkant
    Omkant over 11 years
    No.. I said that if free(ptrobj) is done then firstname and suname pointers are the members on the heap which is gone , so the memory allocated by firstname and suname will not be freed because to free it you will have to write free(firstname) but firstname no longer exist ..hopw you got it
  • dierre
    dierre over 3 years
    @user10099 the reason of the memory still being there is because it wasn't still cleaned by the OS. The reason you can still access that info is for that reason, so actually if access a portion of memory after calling free it's called "undefined behavior"
  • user10099
    user10099 over 3 years
    @dierre thanks, after 8 years the memory somehow got cleaned itself
  • dierre
    dierre over 3 years
    Ops I didn’t notice how old the thread was. But I’m glad the situation fixed itself!