Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does GCC not attempt memory leak checking?

While I rarely use C anymore, I was thinking about the rule I was always told that "if you call malloc() (or new), you must call free() (or delete)". It brought me to wondering if GCC (or another C compiler) attempts to perform any kind of memory and warn the user of a potential issue. I never heard about it, so I suspected it wasn't the case, but I wanted to find out.

Here's the example I used:

#include <stdlib.h>

int main() {
  int* first = malloc(sizeof(int) *  10);
  int* second = malloc(sizeof(int) * 10);

  int i = 0;
  for (; i < 10; i++) {
    first[i] = i * 2;
    second[i] = i * 10;
  }

  free(first);  /* Forgot to free second */
  return 0;
}

When compiling with gcc -Wall free_test.c no warnings were generated. While I can see why the compiler cannot provide a perfect answer because you're dealing with heap memory and managing this at run time, why does the compiler not appear to attempt to provide a warning that there could be a memory leak?

Some of my thoughts on why include:

  1. The compiler may not have a perfect way of telling when memory is freed. For example, if one of those pointers was passed into a function and freed from within the function, the compiler may not be able to tell that.
  2. If a different thread takes ownership of the memory, the compiler would not have any way to tell that somebody else could be freeing memory.
like image 637
pseudoramble Avatar asked Dec 12 '22 07:12

pseudoramble


1 Answers

Cases that can't be detected via static analysis (let alone via trivial static analysis) vastly outnumber those that can. The compiler authors presumably decided the benefits of adding this extra complexity to GCC was outweighed by the costs.

like image 104
Oliver Charlesworth Avatar answered Dec 28 '22 12:12

Oliver Charlesworth