[PATCH] glibc/manual/examples: add missing free to open_memstream example

Andreas Schwab schwab@suse.de
Tue Jun 24 07:47:12 GMT 2025


On Jun 23 2025, Collin Funk wrote:

> Hi Ravina,
>
> Ravina Jain <rajulravina123@gmail.com> writes:
>
>>    printf ("buf = `%s', size = %zu\n", bp, size);
>> +  free(bp);
>
> It should be formatted as "free (bp)".
>
> However, I don't think this is necessary. It is common to not free
> memory when the program is going to just exit anyways. Here is what the
> GNU Coding Standards say [1]:
>
>     Memory analysis tools such as valgrind can be useful, but don’t
>     complicate a program merely to avoid their false alarms. For
>     example, if memory is used until just before a process exits, don’t
>     free it simply to silence such a tool.
>
> We can see this behavior in 'ls' for example:
>
>     $ valgrind ls -la --human-readable 2>&1 | grep 'still reachable'
>     ==167809==    still reachable: 33,792 bytes in 217 blocks

In this toy example it is seen by valgrind as an unreachable block, and
thus a true leak.

$ valgrind --leak-check=full ./memstrm
==1015== Memcheck, a memory error detector
==1015== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==1015== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
==1015== Command: ./memstrm
==1015== 
buf = `hello', size = 5
buf = `hello, world', size = 12
==1015== 
==1015== HEAP SUMMARY:
==1015==     in use at exit: 13 bytes in 1 blocks
==1015==   total heap usage: 4 allocs, 3 frees, 9,733 bytes allocated
==1015== 
==1015== 13 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1015==    at 0x48489BC: realloc (vg_replace_malloc.c:1690)
==1015==    by 0x491DAD3: _IO_mem_finish (memstream.c:103)
==1015==    by 0x4913DCC: fclose@@GLIBC_2.2.5 (iofclose.c:57)
==1015==    by 0x400697: main (memstrm.c:32)
==1015== 
==1015== LEAK SUMMARY:
==1015==    definitely lost: 13 bytes in 1 blocks
==1015==    indirectly lost: 0 bytes in 0 blocks
==1015==      possibly lost: 0 bytes in 0 blocks
==1015==    still reachable: 0 bytes in 0 blocks
==1015==         suppressed: 0 bytes in 0 blocks
==1015== 
==1015== For lists of detected and suppressed errors, rerun with: -s
==1015== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from (0)

-- 
Andreas Schwab, SUSE Labs, schwab@suse.de
GPG Key fingerprint = 0196 BAD8 1CE9 1970 F4BE  1748 E4D4 88E3 0EEA B9D7
"And now for something completely different."


More information about the Libc-alpha mailing list