什么是“记忆重击”?

我刚刚来到 在这篇博文中,它提到了“践踏记忆”:

一个 C + + 程序,很容易就能够践踏内存 (一些你可能从来没有听说过的东西,如果你是 生于托管代码世界。)

事实上,我从来没有听说过!

那么,这是什么,记忆践踏,践踏记忆? 什么时候发生的?

17401 次浏览

Very often it is a buffer overrun; as an example, this code:

char buffer[8];
buffer[8] = 'a';

will "stomp" on whatever happens to be in the next thing in memory after buffer. Generally speaking, 'stomping' is when memory is written to unintentionally.

Memory is "stomped" when a piece of code manipulates memory without realizing that another piece of code is using that memory in a way that conflicts. There are several common ways memory can be stomped.

One is allocating, say, 100 bytes of memory but then storing something past the 100th address. This memory might be used to hold something completely different. This is particularly hard to debug because the problem will appear when something tries to access the victim that was stomped on, and the code that stomped on it may be totally unrelated.

Another is accessing memory after it was freed. The memory may be allocated for another object. Again, the code that shows the problem may be related to the newly-allocated object that got the same address and unrelated to the code that caused the problem.

Other answers basically are correct, but I would like to give an example.

int a[10], i;
for (i = 0; i < 11 ; i++)
a[i] = 0;

int i, a[10];
for (i = 0; i < 11 ; i++)
a[i] = 0;

These samples may lead into infinite loop (or may not lead), because it is undefined behavior.

Very likely variable i in memory is stored just after array. So accessing a[10] could actually access i in other words it could reset loop counter.

I think it is good example that demonstrates memory "stomping".