简体   繁体   English

malloc():内存损坏

[英]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. 我使用malloc分配了8192个字节。 Then my program will write more than 8192 characters in to the array. 然后我的程序将超过8192个字符写入数组。 Then I will allocate memory using malloc. 然后我将使用malloc分配内存。

This mini program didn't crash. 这个迷你程序没有崩溃。 But in the original big project, it crashes with this error: 但在最初的大项目中,它崩溃了这个错误:

malloc(): memory corruption: 0x0000000007d20bd0 *** malloc():内存损坏:0x0000000007d20bd0 ***

What may cause this difference? 什么可能导致这种差异?

It is undefined behavior because you have allocated 8192 bytes memory but you are trying to write 9200 bytes. 它是未定义的行为,因为您已分配8192字节的内存但您尝试写入9200字节。 Which is out of bound. 哪个是出界的。

What may cause this difference? 什么可能导致这种差异?

Basically, the memory allocator allocates pages of memory at once for use by programs, and it gives you a pointer within them (making sure the following space is free for use). 基本上,内存分配器一次分配内存以供程序使用,它会在其中为您指定一个指针(确保以下空间可以免费使用)。 Since these pages are usually bigger than 8KiB, you have no issue in your mini-program. 由于这些页面通常大于8KiB,因此您的迷你程序没有问题。 But if a larger program is allocating larger amounts of memory and writing further and further past the end of your allocated space, then you'll end up attempting to write into unallocated memory (or memory used by another program!), thus corrupting memory. 但是如果一个更大的程序分配更大量的内存并进一步写入已分配空间的末尾,那么你最终会尝试写入未分配的内存(或另一个程序使用的内存!),从而破坏内存。

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. 那是因为malloc()返回了你可以写入的一段内存,所以当你写过该区域的末尾时,你会覆盖不属于你的东西。

That could be a structure used by malloc itself, or something else entirely. 这可能是malloc本身使用的结构,或者完全不同的东西。

It is a matter of luck. 这是运气问题。 Your operating system may reserve memory more than the 8kB you requested. 您的操作系统可能会保留超过您请求的8kB的内存。 Also what you have reserved before and after may have an effect on the behaviour. 您之前和之后保留的内容可能会对行为产生影响。

It is not said that your program will crash on buffer overflow. 不是说你的程序会在缓冲区溢出时崩溃。 In fact the behaviour is undefined or implementation defined. 实际上,行为未定义或实现已定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM