Home > Back-end >  Leaks using makefile
Leaks using makefile

Time:12-04

I'm a beginner in C programming and I faced an issue with valgrind, here is my code :

#include <stdio.h>
int main(int argc,char **argv)
{
   printf("Hello World ");
}

When I do a Makefile to run it :

run: compile
     ./a.out

compile: 
        gcc test.c

I run with valgrind make and I have an error that told me that there is a still reachable blocks , when I compile without Makefile I have 0 Error , can someone help me to resolve it ?

CodePudding user response:

I can reproduce your issue if I run

valgrind make

but not if I run

make compile
valgrind ./a.out

The first is testing an entirely different thing (the memory usage of make) than is the second (the memory usage of ./a.out).

Like @MadScientist, I really don't understand why people create plain run targets, but it does make some sense to me that they would create a target to test with valgrind. If you wanted such a target then it would look something like this (in light of the rest of the Makefile):

leakcheck: compile
    valgrind ./a.out

CodePudding user response:

On some systems, the Standard I/O layer of the C Programming Language allocates buffers that valgrind reports as reachable even for tiny programs such as yours.

I have used systems where this is the case. To free the Standard I/O resources you can close the Standard I/O streams before returning from main, as described in the C99 7.21.5.1 Description of fclose

A successful call to the fclose function causes the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by the setbuf or setvbuf function is disassociated from the stream (and deallocated if it was automatically allocated).

The parenthetical remark at the end of that paragraph is the hint.

int main(int argc, char **argv) {
     /* ... */
     fclose(stdin);
     fclose(stdout);
     fclose(stderr);
     return 0;
}
  • Related