alexfru / SmallerC

Simple C compiler
BSD 2-Clause "Simplified" License
1.35k stars 155 forks source link

Memory Leak #53

Open dududuguo opened 2 weeks ago

dududuguo commented 2 weeks ago

env

5.15.133.1-microsoft-standard-WSL2 commit b120a9c389146bc2049dfff5fa16673210c8a12a

issue

$ valgrind --leak-check=full smlrcc 1.c ==81279== Memcheck, a memory error detector ==81279== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==81279== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info ==81279== Command: smlrcc 1.c ==81279== ==81279== ==81279== HEAP SUMMARY: ==81279== in use at exit: 381 bytes in 7 blocks ==81279== total heap usage: 57 allocs, 50 frees, 5,221 bytes allocated ==81279== ==81279== 35 bytes in 1 blocks are definitely lost in loss record 4 of 7 ==81279== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) ==81279== by 0x10C28D: Malloc (smlrcc.c:355) ==81279== by 0x10C28D: SystemFileExists (smlrcc.c:1220) ==81279== by 0x10C4F6: AddSystemPaths (smlrcc.c:1299) ==81279== by 0x109807: main (smlrcc.c:1909) ==81279== ==81279== LEAK SUMMARY: ==81279== definitely lost: 35 bytes in 1 blocks ==81279== indirectly lost: 0 bytes in 0 blocks ==81279== possibly lost: 0 bytes in 0 blocks ==81279== still reachable: 346 bytes in 6 blocks ==81279== suppressed: 0 bytes in 0 blocks ==81279== Reachable blocks (those to which a pointer was found) are not shown. ==81279== To see them, rerun with: --leak-check=full --show-leak-kinds=all ==81279== ==81279== For lists of detected and suppressed errors, rerun with: -s ==81279== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

poc

int main()
{ return 0;}

located issues

char* SystemFileExists(const char* path, int slash, const char* pathsuffix, const char* name)
{
  size_t plen = strlen(path);
  char* p = Malloc(plen + 1/*slash*/ + (pathsuffix ? strlen(pathsuffix) : 0) + strlen(name) + 1/*NUL*/); // leak here
  ....
}

maybe the solution is add free(pinclude); pinclude = NULL; after 1301 line?

alexfru commented 2 weeks ago

Note, the compiler is short-lived, that is, not running continuously for many iterations or long times, so any simple unfreed resource (memory, file descriptor) should generally be OK to be reclaimed by the OS at termination time instead of being freed explicitly.