Frederick said:
In response to those who have replied regarding modification of <stdlib.h>:
I thought the OP had the source code for a program which had a memory
leak, and I thought he wanted to find the memory leak. I thought code which
hijacked "malloc" and "free" might help him find the memory leak. I didn't
mean for the code to be used indefinitely, but rather a "once off" sort of
thing.
This could be a fair assessment, I guess. The problem with handy tweaks
like this is that they assume a sort of naive understanding of the
implementation. I've certainly tweaked system headers in the past (on
early Linux, for example) to test something and then tweaked them right
back.
The problem is that one may introduce related issues that stem from the
system hack that may cause further confusion. I prefer treating the
implementation as a bit of a black box just for this reason.
I have to admit though that I haven't got much experience in the whole
"memory leak" game, as I read back over my code, and a "malloc" without a
corresponding "free" would stick out like a sore thumb to me.
Once your code gets big enough, you can end up having chunks of memory
past around from module to module for the entire lifetime of the app
process. There are no sore thumbs sticking out in the thousand-or-so
lines of code you can keep in your head in cases like this, I find.
That is to say, even shit-hot coders can introduce memory leaks, or
write code where it is easy to introduce memory leaks with maintenance.
C coders just have to be extra careful with the godlike access they
have to memory resources.
It's pretty standard around here, then, to have utility libraries in
scope that do a lot of workhorse stuff. This may actually be the only
chunk of code that includes <stdlib.h>. One such common utility
function is usually a "my_malloc()" which is the only interface to
memory allocation stuff.
Even if, at first, my_malloc() is a simple transparent wrapper around
malloc() it is usually extended at some point to have a compile-time
switch that controls whether plain, default malloc() is used or some
alternative debugging malloc-like routine.
Even if my_malloc() simply counts references/dereferences as you pointed
out earlier, this can be a big help.
I'm actually ignorant of the many static and dynamic memory debug tools
out there, which is why I'm most familiar with this old-skool method of
memory debugging.