Search code examples
cheap-memorydynamic-memory-allocationmicrochip

Is the order of free-ing the allocated memory important? (C language)


I'm coding in C language for PIC32 microcontroller (there is no OS, the compiler is Microchip XC32 v1.33). I use dynamic objects (created by malloc function) but from time to time (not always) I experienced crashes. After much testing it appeared that it is connected with free-ing the memory.

I've googled it a bit and I found some comments that the order of free-ing memory is important. (LINK1, LINK2)

Could anyone explain if free-ing the dynamic memory should be in the reverse order than allocating it?


Solution

  • Lets say that you have a dynamically allocated struct and inside the struct a pointer to dynamic memory, something like this:

    typedef struct
    {
      item_t* items;
    } note_t;
    

    A metaphor would be stock in a warehouse. First you create a note containing the shelf number (address/pointer) where some items are stored:

    note_t* note = malloc(sizeof *note);
    

    (which could optionally also explain what those items are for, with a better variable name than note)

    You'd pick a suitably large shelf depending on the number of items:

    note->items = malloc( sizeof(item_t[large_enough]) );
    

    Then you move the actual items there:

    memcpy(note->items, src, sizeof(item_t[large_enough]));
    

    Whenever you need those items, you can use that note to go to the shelf and find the items there:

    note->items
    
    // or specific item number i:
    note->item[i]
    

    Now you decide to throw away the items - they no longer fill a purpose. If you throw away the note the first thing you do, then how would you know where to find the items?

    // BAD
    free(note);
    // note->items is now a memory leak
    

    They will still sit there somewhere in the warehouse taking up space, but now nobody knows what they are for. Sure you could rush back and dive into the garbage dumpster and pick up the note from it, maybe it's still readable - but there are no guarantees of that. It might as well have coffee stains and old glue all over it, making it unreadable or worse - sending you to the wrong location.

    Instead start by going to the shelf and removing the items and when that's done, you can safely throw away the note as well:

    free(note->items);
    free(note);
    

    Metaphors aside, you should not use dynamic memory allocation on a bare metal embedded system. There is a long list of reasons why you shouldn't, and no reasons why you should. See Why should I not use dynamic memory allocation in embedded systems?