# valgrind: Why should I close stdin and stdout?



## ishpeck (May 17, 2013)

When I use Valgrind, it reports that there is some memory still reachable at exit -- as if I weren't free()'ing something.  If I fclose() stdin, stdout, and stderr, Valgrind doesn't complain.


```
[0] [ishpeck@kiyoshi tinker]% cat hi.c 
#include <stdio.h>

int main(void) {
    printf("Howdy.\n");
    return 0;
}
[0] [ishpeck@kiyoshi tinker]% clang -o hi hi.c 
[0] [ishpeck@kiyoshi tinker]% ./hi 
Howdy.
[0] [ishpeck@kiyoshi tinker]% valgrind ./hi
==33618== Memcheck, a memory error detector
==33618== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==33618== Using Valgrind-3.8.0 and LibVEX; rerun with -h for copyright info
==33618== Command: ./hi
==33618== 
Howdy.
==33618== 
==33618== HEAP SUMMARY:
==33618==     in use at exit: 4,096 bytes in 1 blocks
==33618==   total heap usage: 1 allocs, 0 frees, 4,096 bytes allocated
==33618== 
==33618== LEAK SUMMARY:
==33618==    definitely lost: 0 bytes in 0 blocks
==33618==    indirectly lost: 0 bytes in 0 blocks
==33618==      possibly lost: 0 bytes in 0 blocks
==33618==    still reachable: 4,096 bytes in 1 blocks
==33618==         suppressed: 0 bytes in 0 blocks
==33618== Rerun with --leak-check=full to see details of leaked memory
==33618== 
==33618== For counts of detected and suppressed errors, rerun with: -v
==33618== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
[0] [ishpeck@kiyoshi tinker]% cat hi2.c 
#include <stdio.h>

int main(void) {
    printf("Howdy.\n");
    fclose(stdin);
    fclose(stdout);
    fclose(stderr);
    return 0;
}
[0] [ishpeck@kiyoshi tinker]% clang -o hi2 hi2.c 
[0] [ishpeck@kiyoshi tinker]% ./hi2 
Howdy.
[0] [ishpeck@kiyoshi tinker]% valgrind ./hi2
==33628== Memcheck, a memory error detector
==33628== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==33628== Using Valgrind-3.8.0 and LibVEX; rerun with -h for copyright info
==33628== Command: ./hi2
==33628== 
Howdy.
==33628== 
==33628== HEAP SUMMARY:
==33628==     in use at exit: 0 bytes in 0 blocks
==33628==   total heap usage: 1 allocs, 1 frees, 4,096 bytes allocated
==33628== 
==33628== All heap blocks were freed -- no leaks are possible
==33628== 
==33628== For counts of detected and suppressed errors, rerun with: -v
==33628== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```

This exact same code won't report any memory as "still reachable" on other platforms (such as Linux and OpenBSD). Is this a characteristic of FreeBSD or is it a symptom of something in the port of Valgrind?


----------



## ta0kira (May 21, 2013)

It could be that other libc implementations clean up those buffers on exit. In any case, unfreed but reachable memory isn't a big deal by itself.

Kevin Barry


----------

