-2

i was playing arround with the C malloc and free tools and i had a weird memory leak. Does someone has an idea about it?

The goal is to successfully free a char**.

So in the function freezer, i free every char* in the char** and the i free the char**.

But Valgrind (my leaks detector on linux) find 20 bytes in 4 blocks leaked (i don't know if i can write 'leaked' XD) The more interesting part is that if i do a bigger char** by adding a char* in it, it leak 5 more bytes of memory in another block :/.

#include <stdio.h>
#include <stdlib.h>
void    freezer(char ***array, int length){
    int i;

    i = -1;
    while (*array[++i] != NULL){
        free(*array[i]);
    }
    free(*array);
}

int     main(){

    char    **big;
    int len = 4;
    int i;

    big = malloc(sizeof(char *) * (len + 1));
    i = -1;
    while (++i < len){
        big[i] = malloc(sizeof(char) * 5);
        big[i][0] = 't';
        big[i][1] = 'e';
        big[i][2] = 's';
        big[i][3] = 't';
        big[i][4] = '\0';
    }
    big[i] = NULL;
    i = -1;
    while (++i < len){
        printf("i: %d\t%s\n", i, big[i]);
    }
    freezer(&big, len);
    return (0);
}

You can directly copy/past/run the code as it is.

So if you have any clue about the error/C problem, please let me know.

MrBouh
  • 260
  • 1
  • 15
  • Please don't edit the answer into the question, it makes things weird for future readers. (Although the edit is actually incorrect, `*array[++i]` should be `(*array)[++i]`, and similarly for the following line) – M.M Nov 27 '15 at 00:12

1 Answers1

0

big[i] = NULL; causes a buffer overflow. You only allocated space for a total of len entries, plus one byte; but at that point i == len.

Perhaps you meant big = malloc(sizeof(char *) * (len + 1));

Also, the freezer function dereferences and frees the wrong thing. Either change it to accept char **array , or replace all occurrences of array with (*array) inside the function. The former is preferable, there is no need to pass by reference in order to call free.


Your loop structure is weird for no apparent reason; it's normal to use:

for (i = 0; i < len; ++i)

which is the same logic but will make your code easier to digest for people reading it.

Also, don't cast malloc

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
  • thanks, i don't know how the f**** i missed those XD The while instead of the for comes from my school rules which forbid the use of the for loop for no true good reason. – MrBouh Nov 27 '15 at 00:05