views:

97

answers:

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

Why heap corruption happens at free (b);?IMO heap corruption already happens at *b=110000;,what do you think?

+10  A: 

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.

Ned Batchelder
My question is why `*b=110000;` doesn't corrupt since it's using more space than available?
Alan
It is the assignment that corrupts the heap, it's the free call that detects the corruption.
Ned Batchelder
@Alan - It does corrupt your heap. Just that you may or may not see the consequences immediately.
Manoj R
-1, This is good advice on how to make a correct program but it doesn't answer the question.
Edmund
@Edmund ,@Ned Batchelder's comment is actually the answer,I'll accept it when time permits.
Alan
agree, this is not answer.
Andrey
@Alan answer should be: "It is because ... . Do this to fix ... ."
Andrey
Ned Batchelder
+4  A: 

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.

Manoj R
+3  A: 

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).

Bart van Ingen Schenau
A: 

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.

IronMaiden