Search code examples
cmemorystructmallocfree

Cannot figure out how to free my structure


I need to free() all the memory allocated for my structure config.

struct keysnvalues {
char* key;
char* value;
};

struct section {
char *name;
struct keysnvalues *keysnvalues;
int keysnvalues_ammount;
};

struct config {
struct section *sections;
int section_ammount;
};

In the beggining of the code I do this

struct section * sect = malloc(sizeof(struct section) * 255);
struct keysnvalues * keysnvalue = malloc(sizeof(struct keysnvalues) * 255);

If I want to add section I do this for the first one

sect[++num_section].name = buffer; // buffer is the name

And for the next sections

sect[num_section].keysnvalues = keysnvalue;
sect[num_section].keysnvalues_ammount = num_keysnvalues;
cfg -> section_ammount++;

            //start with new keysnvalue
num_keysnvalues = 0;
keysnvalue = malloc(sizeof(struct keysnvalues) * 255);
sect[++num_section].name = buffer;
sect[num_section].keysnvalues = 0;

If I want to add a key and a value to section I am working with I do this

keysnvalue[num_keysnvalues].key = key;
keysnvalue[num_keysnvalues++].value = value;

The whole code is here: https://pastebin.com/pGztJ9k4

I am aware of the fact that this is probably a stupid question, but I could not figure out how to free the whole structure config for hours now.

I would really appreciate your help.


Solution

  • Generally, you should free() a pointer if and only if it has been allocated through malloc(). To achieve this, you have to make sure not to "loose" any pointer to a malloced memory address, e.g. by assigning malloc several times to the same variable without having copied it's previous value or without having freed the previously assigned memory.

    I did not analyse the complete code you referred to. But it seems as if you copy the value of keysnvalue to the current section before mallocing a new value for sect[i].keysnvalues. Hence, it seems that each section get's its own keysnvalue, and you can loop it through:

    for (int i=0;i< num_section;i++) {
       if (sect[i].keysnvalues != NULL) {
          free(sect[i].keysnvalues);
          // free(sect[i].name);  // if buffer has also been malloced
       }
    }
    free (keysnvalue);
    free (sect);
    

    It may be that you also have to loop trough each sect[i].keysnvalue in order to eventually free key/value.

    Make sure that section members that you are going to free at the end of the program are always initialised either with NULL or a malloced value in order to prevent your code from "freeing" a garbage pointer value.