Question

int main ()
{
    int * b;
    b = (int*) malloc (1);
    *b=110000;
    free (b);
    return 0;
}

Why does heap corruption happen at free (b);?

IMO, heap corruption already happens at *b=110000;.

Was it helpful?

Solution

malloc()'s argument is the number of bytes to allocate. You need to use:

b = (int*) malloc(sizeof(int));

You've allocated too small a block, and then written more bytes to it than you've allocated, which overwrites bookkeeping information next to the block, corrupting the heap.

OTHER TIPS

It is at *b=110000; Because you are allocating the memory for one byte, and then assigning an int into it which is more than one byte. Either you can have b= (int *)malloc(sizeof(int)) or instead of int *b you can have char *b and then cast the malloced pointer to char *. The code will even may work if you assign a value which is less than 128 (because of signed char) to *b.

EDIT :- I think sometimes even this will work without any hassle. Because the compiler may choose to allocate more than one byte of memory for fast access of data.

The heap corruption indeed happens already at the *b=11000 assignment, but it is not detected until the free(b) call because that is the first point where the integrity of the heap gets checked again.

Checking the heap integrity at every assignment (or even every assignment involving a dereferenced pointer) would slow most programs down too much and it would tie the compiler too tightly to the library implementation. For that reason, the integrity checks are only performed when the heap gets manipulated, which is in the malloc and free functions (and friends).

The code writes more data to the memory block than the space available to it hence corrupting the start of next valid memory block.

Using char * rather than int * and writing a value -128 to 127 to *b should fix it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top