Hello! I have a question in regards to malloc/calloc and free in C. What I'm unsure about is the "depth" (for lack of a better word) that free operates to. I know that sounds strange so let this example hopefully explain what I mean:

#include <stdlib.h>

int main ()
{
    int length = 10;
    char **list = (char **) malloc(sizeof(char *) * length);

    char *temp;
    int i;
    for (i = 0; i < length; i++)
    {
        temp = (char *) malloc(13);
        temp = "Hello world!\0";
        list[i] = temp;
    }

    free(list);  // free the char** AND all of its indices' malloc'd memory?
}

So I was wondering if the last call of free would not only free up the char ** memory of "list", but also all the malloc'd memory of each of its indices? Or does it not, and should in fact be called via:

for(i = 0; i < length; i++)
    free(list[i]);
free(list);

... which would explicitly free each index before the pointer to char pointers.

So would some compilers know that only freeing the list should free all its indices, or would I always get a memory leak with that? Either way, I want to know if there's an ANSI standard on this... which is probably the second method here if anything.

Thanks in advance for clearing up my confusion!

Recommended Answers

All 2 Replies

So would some compilers know that only freeing the list should free all its indices, or would I always get a memory leak with that? Either way, I want to know if there's an ANSI standard on this... which is probably the second method here if anything.

Thanks in advance for clearing up my confusion!

Number one its the memory manager that handles allocation/freeing of memory not the compiler. The compiler generates the code that calls the memory manager.

Basically you have to call free for each successful malloc you call....or you could exit the program and let the exit procedures clean up the memory for the program...

I knew it was the memory manager of the OS, but I just wasn't sure if the compiler generated code to call it for all the indices or not. I'll take it then that the second snippet with the other for loop is the correct way. Thanks for confirming it for me!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.