我在玩动态大小内存池的想法,然后玩,我最终得到了一些我确信会失败但没有失败的代码。这是代码:
#include <iostream>
using namespace std;
struct largeStruct
{
largeStruct()
{
X = 123456789;
Y = 987654321;
str = "Hy! Here I am, a c string, out in the wild c++, the place where your pointers dangle and your friends play with your privates";
}
unsigned long long X;
unsigned long long Y;
char* str;
};
int main()
{
void* ptr = new unsigned char[sizeof(largeStruct)];
largeStruct a;
*((largeStruct*)ptr) = a;
cout << "Size of data: " << sizeof(largeStruct) << endl;
cout << "Data: " << endl;
cout << ((largeStruct*)ptr)->X << endl
<< ((largeStruct*)ptr)->Y << endl
<< ((largeStruct*)ptr)->str << endl
<< endl;
delete[] ptr;
}
这适用于我的电脑(Windows 8,MSVC Express 2012)。虽然在其中添加了更多内容,但我认为,虽然是 hack,但它是有道理的。内存中的数组是这样的:
===================================
... || a0 || a1 || a2 || ...
===================================
因此,当您尝试存储大于数组成员之一的值时,它会访问侧面的内存。因此,尝试存储 3 个块大小的值将起作用,并最终如下所示:
====================================
... || data data data data || ...
====================================
那么,这是危险的,还是某种晦涩难懂的无害黑客?