内存泄漏 | LeakSanitizer:检测到内存泄漏 | C编程

Memory leak | LeakSanitizer: detected memory leaks | C programming

我不明白为什么会发生下面的内存泄漏,以及如何避免它。

我正在使用 malloc 分配内存,我用一个循环启动这个分配的内存,将一个值一个值地从字符串 a 复制到字符串 b.

据我所知,我不会留下任何未使用的内存。

我的代码:

#include <stdlib.h>

void    run_test_one(void)
{
    char    *a;
    char    *b;
    int     i;

    a = "up the irons";
    b = (char *)malloc(13 * sizeof(char));
    i = 0;
    while(a[i] != '[=10=]')
    {
        b[i] = a[i];
        ++i;
    }
    b[i] = '[=10=]';
}

int main(void)
{
    run_test_one();

    return (0);
}

错误:

==9003==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 13 byte(s) in 1 object(s) allocated from:
    #0 0x7ffb28c1db40 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb40)
    #1 0x55a9533b29c6 in run_test_one test.c:10
    #2 0x55a9533b2b04 in main test.c:22
    #3 0x7ffb2876fbf6 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)

SUMMARY: AddressSanitizer: 13 byte(s) leaked in 1 allocation(s).

不管用不用,内存都是malloc分配的。要修复泄漏,您需要释放内存。

#include <stdlib.h>

void    run_test_one(void)
{
    char    *a;
    char    *b;
    int     i;

    a = "up the irons";
    b = (char *)malloc(13 * sizeof(char));
    i = 0;
    while(a[i] != '[=10=]')
    {
        b[i] = a[i];
        ++i;
    }
    b[i] = '[=10=]';
    // new code
    free(b)
    // 
}

int main(void)
{
    run_test_one();

    return (0);
}

第二种解决方案是使用自动分配。在您的程序离开后 run_test_one 函数内存被释放:

#include <stdlib.h>

void    run_test_one(void)
{
    char    *a;
    char    *b;
    int     i;

    a = "up the irons";
    //edit
    char b[13];
    //
    i = 0;
    while(a[i] != '[=11=]')
    {
        b[i] = a[i];
        ++i;
    }
    b[i] = '[=11=]';
}

int main(void)
{
    run_test_one();

    return (0);
}