C++ 读/写数组越界 [英] C++ read/write to array out of bounds
问题描述
可能已经在某处找到了答案,但我找不到.
There's probably already an answer to this somewhere, but I can't find it.
如本问题所述:访问数组越界没有错误,为什么?,C++ 不强制数组边界,而是选择提供未定义的行为.我担心的是这种行为的威力.
As noted in this question: Accessing an array out of bounds gives no error, why?, C++ does not enforce array bounds, instead opting to provide undefined behavior. What I'm concerned about is the power of this behavior.
假设我写了一些简单的程序:
So suppose I write some simple program:
#include <iostream>
int main() {
int* a = new int[1];
long large_number = 9223372036854775807l; //2**63 - 1
for (long i = 0l; i < large_number; i++) {
std::cout << i << " " << a[i] << std::endl;
}
return 0;
}
这将继续打印存储在我系统上的下一个 32 位数字(显然,假设是 32 位大小的整数).当我在我的机器上运行它时,当我大约 30,000 时,程序出现段错误,我猜这大约是为我的程序分配的内存大小.这让我想到了我的三个问题:
This will continue to print the next 32-bit number stored on my system (assuming 32 bit-sized ints, obviously). When I run this on my machine, the program segfaults when i is around 30,000, which I'm guessing is around the size of the memory allocated for my program. This brings me to my question, which is three-fold:
是什么阻止我继续读取(而不是写入)此范围之外的值?这种防止阅读系统是特定的吗?特定于编译器?
What's preventing me from continuing to read (not write) values outside this range? Is this prevention of reading system-specific? Compiler-specific?
如果我对如何操作指针很聪明,我是否可以读取或写入程序范围之外的值(显然,无需直接/正常访问这些值)?
If I was clever with how I manipulate my pointer, could I read or write values outside of the scope of my program (without, obviously, having direct/normal access to these values)?
我在虚拟机上运行所有这些.我可以访问主机上的读/写内存值吗?(如果(2)是否定的,那么这也是否定的).
I'm running all of this on a virtual machine. Can I access read/write memory values on my host machine? (If (2) is a no, then this is a no as well).
请注意,我在带有 Windows 主机的 ubuntu virtualbox 上运行 g++ 5.3.1,没有 c++11.
Note that I'm running g++ 5.3.1, no c++11, on a ubuntu virtualbox with a windows host machine.
另外,我认识到这个问题可以被认为是一个安全问题(读/写内存).我当然没有恶意,但如果这是一个问题,请告诉我,我很乐意结束这个问题.
Also, I recognize this question could be considered a security issue (reading/writing memory). I'm certainly not intending anything malicious, but if this is a problem, let me know and I will be glad to close the question.
以下问题似乎相关且有趣:访问程序分配的内存之外.(访问其他应用的内存)不过,对于程序是否可以在其虚拟内存空间之外进行读取,似乎并没有达成共识.
The following question appears related and interesting: Accessing outside the memory allocated by the program. (Accessing other app's memory) There doesn't seem to be a consensus on whether or not a program can read outside of it's virtual memory space though.
推荐答案
操作系统.操作系统仅将一定范围的虚拟地址映射到物理地址.到达映射的虚拟地址范围的末尾后,尝试访问不存在的虚拟地址会生成
SIGSEGV
.
没有.至少在任何现代操作系统上都不会.
No. At least not on any modern operating system.
除非您能在主机操作系统的虚拟机中找到错误并加以利用.
Not unless you can find a bug in your host operating system's virtual machine, and exploit it.
这篇关于C++ 读/写数组越界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!