简体   繁体   中英

Using command leaks

I'm having a hard time understanding why the command leaks is outputting that there is no memory leaks in this simple program. Am I using it wrong?

#include <stdlib.h>
#include <stdio.h>

int main()
{
    char *str;
    str = malloc(sizeof(str) * 15);
    system("leaks a.out");
    return 0;
}

I compile it with gcc main.c And run with ./a.out

The output is:

leaks Report Version: 4.0
Process 94181: 156 nodes malloced for 8 KB
Process 94181: 0 leaks for 0 total leaked bytes.

Since I allocated memory and didn't free it, there should be leaks, right?

It hasn't leaked yet. The memory is still accessible.

I'm not familiar with leaks (and I can't find where to find it), but I suspect you'll get a leak reported if you were to use the following:

char *str;
str = malloc(sizeof(str) * 15);
str = NULL;
system("leaks a.out");

Note that with gcc (and clang?), you can use -fsanitize=address to find leaks. As this demo on Compiler Explorer shows, you get the following output when the program ends:

=================================================================
==1==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 120 byte(s) in 1 object(s) allocated from:
    #0 0x7f99f29007ef in __interceptor_malloc (/opt/compiler-explorer/gcc-11.2.0/lib64/libasan.so.6+0xb17ef)
    #1 0x401187 in main /app/example.c:7
    #2 0x7f99f26810b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x240b2)

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

There is also valgrind .

[...]
==9055== HEAP SUMMARY:
==9055==     in use at exit: 120 bytes in 1 blocks
==9055==   total heap usage: 1 allocs, 0 frees, 120 bytes allocated
==9055==
==9055== 120 bytes in 1 blocks are definitely lost in loss record 1 of 1
==9055==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==9055==    by 0x10915E: main (in /tmp/ikegami/a/a)
==9055==
==9055== LEAK SUMMARY:
==9055==    definitely lost: 120 bytes in 1 blocks
==9055==    indirectly lost: 0 bytes in 0 blocks
==9055==      possibly lost: 0 bytes in 0 blocks
==9055==    still reachable: 0 bytes in 0 blocks
==9055==         suppressed: 0 bytes in 0 blocks
[...]

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