Heap corruption in C

倖福魔咒の 提交于 2021-02-19 05:10:02

问题


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


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/3923290/heap-corruption-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!