Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc(): memory corruption

Here is the simplified program that I think can lead to this error.

char *p = (char*)malloc(8192);
for(int i = 0; i < 9200; ++i){
  p[i] = '1';
}
char *s = (char*)malloc(strlen(p)); 

The original project is rather complicated, so I simplified it. I assigned 8192 bytes using malloc. Then my program will write more than 8192 characters in to the array. Then I will allocate memory using malloc.

This mini program didn't crash. But in the original big project, it crashes with this error:

malloc(): memory corruption: 0x0000000007d20bd0 ***

What may cause this difference?

like image 859
Yuan Wen Avatar asked Apr 24 '17 10:04

Yuan Wen


People also ask

What is malloc (): memory corruption?

Writing to memory which you have not allocated is undefined behaviour. That's because malloc() returns a section of memory which you may write to, so when you write past the end of that region, you are overwriting something which is not yours.

What causes corrupted memory?

The most likely causes of memory corruption are programming errors (software bugs). When the corrupted memory contents are used later in that program, it leads either to program crash or to strange and bizarre program behavior. Nearly 10% of application crashes on Windows systems are due to heap corruption.

What is memory corruption error?

Definition: Memory corruption can be described as the vulnerability that may occur in a computer system when its memory is altered without an explicit assignment. The contents of a memory location are modified due to programming errors which enable attackers to execute an arbitrary code.


1 Answers

It is undefined behavior because you have allocated 8192 bytes memory but you are trying to write 9200 bytes. Which is out of bound.

like image 182
msc Avatar answered Oct 14 '22 20:10

msc