Heap corruption in C

Alan picture Alan · Oct 13, 2010 · Viewed 7.1k times · Source
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;.

Answer

Ned Batchelder picture Ned Batchelder · Oct 13, 2010

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.