简体   繁体   English

C 内存泄漏与 char **

[英]C Memory leaks with char **

i was playing arround with the C malloc and free tools and i had a weird memory leak.我正在玩 C malloc 和免费工具,我有一个奇怪的内存泄漏。 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**.所以在函数冻结器中,我释放了 char** 中的每个 char*,而 i 释放了 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 :/.但是 Valgrind(我在 linux 上的泄漏检测器)发现 4 个块中有 20 个字节泄漏(我不知道我是否可以写“泄漏”XD)更有趣的部分是,如果我通过添加一个 char* 来做一个更大的 char**在其中,它在另一个块中泄漏了另外 5 个字节的内存:/。

#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.因此,如果您对错误/C 问题有任何线索,请告诉我。

big[i] = NULL; causes a buffer overflow.导致缓冲区溢出。 You only allocated space for a total of len entries, plus one byte;您只为总共len个条目分配了空间,再加上一个字节; but at that point i == len .但那时i == len

Perhaps you meant big = malloc(sizeof(char *) * (len + 1));也许你的意思是big = malloc(sizeof(char *) * (len + 1));

Also, the freezer function dereferences and frees the wrong thing.此外, freezer函数会取消引用并释放错误的东西。 Either change it to accept char **array , or replace all occurrences of array with (*array) inside the function.要么将其更改为接受char **array ,要么在函数内用(*array)替换所有出现的array The former is preferable, there is no need to pass by reference in order to call free .前者更可取,无需通过引用传递即可调用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另外, 不要施放 malloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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