简体   繁体   中英

C Memory leaks with char **

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM