I accidentally saw a post on program debugging on chinaunix, which discussed many methods for debugging the program. One of the methods is as follows and I think it is not bad:
If there are a lot of malloc in other programs, I don't know where the memory is out of bounds,
Redefines malloc and free in a header file, such as mem. h.
Re-compile the code using gcc-include mem. h to check memory problems without modifying others' code.
(Similarly, You need to redefine strdup, realloc, and other functions)
The Code is as follows: # define magic_num 0x11121314
/*
Magic_num is a random integer that is used as an additional sign for original memory allocation. Therefore, this number should be set to a value with a low probability. Do not use the 0x00000000 value to show a high probability, this method is used to reduce the probability of errors in this method. That is to say, the method still has errors at a low probability.
*/
Static void * my_malloc (size_t size)
{
Int magic = (INT) magic_num;
Char * P = malloc (size + sizeof (size) + sizeof (MAGIC ));
Memcpy (& P [0], & size, sizeof (size_t ));
Memcpy (& P [size-sizeof (MAGIC)], magic, sizeof (MAGIC ));
Return (void *) (p + sizeof (size ));
}
# UNDEF malloc
# Define malloc my_malloc
Static void * my_free (void * PTR)
{
Size_t size;
Int magic;
Char * P = (char *) PTR-sizeof (size );
Memcpy (& size, P, sizeof (size ));
Memcpy (& magic, & P [size + sizeof (size)], sizeof (MAGIC ));
If (magic! = (INT) magic_num)
{
Fprintf (stderr, "memory overflow! N ")
Fflush (stderr );
While (1 );
}
Free (P );
}
# UNDEF free
# Define free my_free