Click to See Complete Forum and Search --> : Malloc and Free
Dave2001
May 6th, 1999, 11:55 PM
In debug mode, if I malloc something, open and close a file, and then try to free the memory of the previous malloc, it gives me a debug assertation error saying that "damage after block..." I realize that I could run it in release mode or just not free the memory, but I want to know how to fix this. What could be causing this and how could I fix it?
Thanks.
Dave2001,
Dave2999@hotmail.com
real name
May 7th, 1999, 01:30 AM
quite problematic to answer
try to give smallest possible example of source where it still happends
Roger Osborn
May 7th, 1999, 02:14 AM
It could just be writing through a bad pointer, but for that particular error it's often copying a string off the end of a block.
Using new it would be stuff like:
char *p=new char(4);
strcpy(p,"abc"); // damage block here
instead of
char *p=new char[4];
strcpy(p,"abc");
Another way is forgetting to allocate space for the trailing NULL. e.g.
char *p=new char[strlen("abc")];
strcpy(p,"abc");// 1 char too short, damages block
The principle is the same for malloc.
You can bracket potentially dodgy stuff with
ASSERT(AfxCheckMemory());
and in Debug runs the one that asserts will be the one following the bad operation. If you're not using MFC then you'd probably need to look at _CrtCheckMemory() instead (same idea though).
Cheers,
Roger
Paul McKenzie
May 7th, 1999, 05:15 AM
You're overwriting passed the memory that was allocated. Someone will correct me if I'm wrong, but I believe that the error message is generated when one of the "guard" bytes is overwritten. The guard bytes are extra bytes that are attached to the memory that you allocated. They're initialized to a value when the malloc() is called, and checked when free() is called. If the value of the guard bytes are not the same as it started out with, then you inadvertantly stepped on something outside the boundaries of the allocated area.
The worst thing that you can do is not fix it. The second worst is not freeing the memory. To be honest, you can't really know whether you can run it in release mode safely, since the bad block causes undefined behavior. Depending on the machine and/or what other programs are running, you're program may exit OK, or get you a fatal error with the dreaded GPF error box stating "Invalid Page Fault".
Regards,
Paul McKenzie
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.