Freeing memory which has been allocated to an array of char pointers (strings). Do I have to free each string or just the “main” pointer?

后端 未结 4 922
春和景丽
春和景丽 2021-02-15 11:26

I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). *list_of_strings* is allocated memory inside the function.



        
相关标签:
4条回答
  • 2021-02-15 11:54

    Yes, you have to free() every block you obtained from malloc(). You do it by traversing the array of pointers and caling free() on each element and only then freeing the array itself.

    Only you know that there's a tree-like structure that could be freed recursively, that knowledge is not anywhere in the C runtime heap, so the heap manager has no idea about that and your program has to free everything itself.

    0 讨论(0)
  • 2021-02-15 11:58

    won't that just free the actual pointers and not the memory each string itself was using?

    Yes, indeed.

    How do I completely free the memory

    By looping through the array and freeing each string one by one before freeing up the array itself. E.g.

    for (i = 0; i < SOMETHING; i++) {
        free(list[i]);
    }
    free(list);
    
    0 讨论(0)
  • 2021-02-15 12:02

    You need to iterate over list and call free() on every array member. Then free the array.

    0 讨论(0)
  • 2021-02-15 12:05

    Basically, there's a rule of thumb to allocating and freeing: You need to call as many free() as you called malloc(). It's as simple as that. In every other case you got yourself a memory leak.

    0 讨论(0)
提交回复
热议问题