[Snek] [PATCH] Close FILE handles with fclose(), as reported by Valgrind

Rhys Kidd rhyskidd at gmail.com
Thu Feb 13 06:56:31 PST 2020


Whilst normal program exit will see open files closed by the operating system,
this is both an implementation detail that may not hold everywhere and leads
to unnecessary message reports in a Valgrind run of snek's test suite.

Using fclose() paired with all fopen() is a good defensive coding practice.

Valgrind heap memory report:

$ valgrind --leak-check=full --show-leak-kinds=all ./ports/posix/snek test/for-range.py
==31140== Memcheck, a memory error detector
==31140== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==31140== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==31140== Command: ./ports/posix/snek test/for-range.py
==31140==
==31140==
==31140== HEAP SUMMARY:
==31140==     in use at exit: 488 bytes in 1 blocks
==31140==   total heap usage: 2 allocs, 1 frees, 4,584 bytes allocated
==31140==
==31140== 488 bytes in 1 blocks are still reachable in loss record 1 of 1
==31140==    at 0x483A7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==31140==    by 0x4A8B9FD: __fopen_internal (iofopen.c:65)
==31140==    by 0x4A8B9FD: fopen@@GLIBC_2.2.5 (iofopen.c:86)
==31140==    by 0x10B9CB: main (snek-main.c:108)
==31140==
==31140== LEAK SUMMARY:
==31140==    definitely lost: 0 bytes in 0 blocks
==31140==    indirectly lost: 0 bytes in 0 blocks
==31140==      possibly lost: 0 bytes in 0 blocks
==31140==    still reachable: 488 bytes in 1 blocks
==31140==         suppressed: 0 bytes in 0 blocks
==31140==
==31140== For lists of detected and suppressed errors, rerun with: -s
==31140== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Signed-off-by: Rhys Kidd <rhyskidd at gmail.com>
---
 hosts/windows/snek-windows.c | 2 ++
 ports/posix/snek-main.c      | 2 ++
 2 files changed, 4 insertions(+)

diff --git a/hosts/windows/snek-windows.c b/hosts/windows/snek-windows.c
index ef6fad3..d110956 100644
--- a/hosts/windows/snek-windows.c
+++ b/hosts/windows/snek-windows.c
@@ -101,6 +101,8 @@ main (int argc, char **argv)
 
 	if (snek_windows_input == stdin)
 		printf("\n");
+	else
+		fclose(snek_windows_input);
 	return ret ? 0 : 1;
 }
 
diff --git a/ports/posix/snek-main.c b/ports/posix/snek-main.c
index 3fd106f..e6465c3 100644
--- a/ports/posix/snek-main.c
+++ b/ports/posix/snek-main.c
@@ -121,5 +121,7 @@ main (int argc, char **argv)
 
 	if (snek_posix_input == stdin)
 		printf("\n");
+	else
+		fclose(snek_posix_input);
 	return ret ? 0 : 1;
 }
-- 
2.20.1



More information about the Snek mailing list