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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With