开发者

Heap corruption in C

开发者 https://www.devze.com 2023-01-19 16:31 出处:网络
int main () { int * b; b = (int*) malloc (1); *b=110000; free (b); return 0; } Why does heap corruption happen at free (b);?
int main ()
{
    int * b;
    b = (int*) malloc (1);
    *b=110000;
    free (b);
    return 0;
}

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

I开发者_如何学PythonMO, heap corruption already happens at *b=110000;.


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.


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.


Your value is 110000 --> 0x01ADB0 --> 3 bytes. You are writing 3 bytes of data into 1 byte you requested from the heap.

It is important to be aware of what malloc is doing with parameter 1, and what you are putting into this memory.

malloc() allocates size bytes and returns a pointer to the allocated memory. Also don't forget to test your pointer before using it, and initializing your local variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消