memory allocation problems
Rog Skubowius
rwskubowius at spurge.uwaterloo.ca
Fri Jan 18 11:08:14 AEST 1991
In article <11589 at arctic.nprdc.navy.mil> asbury at nprdc.navy.mil (Mike Asbury) writes:
>HELP! I have a large program (over 100,000 lines of code) written in Turbo C
>with memory leakage somewhere. I am looking for any programs that will help me
>find C memory allocation errors. Any pointers to shareware or commercial
>programs will be appreciated.
> Thanks in advance,
> Mike
My first question to you is whether or not you have any function
calls 'farmalloc(), farfree(), or farrealloc()'? Also, what version
of the compiler are you using? If it is Turbo C++ v.1.0, the problem
may not be yours. I found a bug in their farrealloc() call when
I was asking for about 650K of total memory. The screen memory
is overwritten by Turbo as it thinks this is valid 'usable' memory.
Anyway, back to your problem. I encourage you to write 3 ( or
possibly 6 ) routines, 1 per C dynamic function routine. For
instance, CheckMalloc(), CheckFree(), CheckRealloc(). If you
use a prefixing ( & possibly postfixing ) signature on the allocated
buffer, & embed the buffer size as well, you can easily fix this
problem & find the bug. Let me show this:
unsigned short CheckMalloc( void ** buffer, unsigned short size )
{
The application on top of CheckMalloc() wants 'size' bytes,
but instead, now call malloc() for 'size' + say 3. Then, write
the letters 'foo' in the first 3 bytes of the allocated memory
& assign (*buffer) to the next byte following the 'foo' signature.
fooXXXXXXXXX -> where a pointer to the 1st X is returned
-> through (*buffer) to the calling function.
}
void CheckFree( void * buffer )
{
Now, if the application has corrupted the buffer, you can
determine it here. You see, *(buffer - 3) == 'f',
*(buffer - 2) == 'o', *(buffer - 1) == 'o'. You should really
macro the checking signature, its length and then use
strncpy() to do the checking of signature. Anyway, if this
doesn't check out...bang...you've caught some memory corruption
as either the original 'CheckMalloc()'d pointer was moved, or
someone overwrote part of your buffer.
}
CheckRealloc()
{
Pretty obvious what to do here --> Check out the signature
& act accordingly.
}
This whole scheme can be improved by using a signature at the
start & one at the end as well, and then putting the allocated
buffer size in the buffer itself so that the end of application
buffer & start of end signature can be found. Dig?
More information about the Comp.lang.c
mailing list