Search code examples
cmemorystructmallocfree

C programming: Freeing nested multidimensional arrays inside structs


EDIT: I'm closing this question due to poor formulation as suggested by coderredoc.

I had a problem with a free function where I mistakenly put the address of a location an argument.

    void freeMemory(Stack stp, int n){
    for(int i=0; i<n; i++){
        free(&(stp.signals[n].intervals));
    }
    free(stp.signals);

}

This is the correct code (look below for more info)

    void freeMemory(Stack stp, int n){
    for(int i=0; i<n; i++){
        free(stp.signals[n].intervals);
    }
    free(stp.signals);

}

Solution

  • Always remember one thing, you will pass to free whatever you have allocated using malloc and it's friends.

    Here you have passed free(&(stp.signals[i].intervals)); why do you pass the address of stp.signals[i].intervals it's stp.signals[i].intervals which contains the allocated chunk's address. (the starting address of the memory chunk that was just created using *alloc) So free(stp.signals[i].intervals) is the correct way to free it.

    To be precise, what you have done here is undefined behavior.

    From standard 7.22.3.3p2

    The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.