A Method for debugging out-of-bounds C program memory

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.