本文介绍了它如何获得比我想要的更多的内存?(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用1个整数的内存,但是该程序如何工作?
I wanted to take a 1 integer memory, but how this program can work?
代码:
#include<iostream>
using namespace std;
int main(){
int* k=new int[1];
for(int i=0;i<5;i++)
cin>>k[i];
for(int i=0;i<5;i++)
cout<<k[i]<<"\n";
delete[] k;
return 0;
}
输入:
999999
999998
999997
999996
999995
输出:
999999
999998
999997
999996
999995
推荐答案
您通过访问未分配的内存来调用未定义的行为.这纯属偶然"的工作.从字面上看,您程序的每种行为都是合法的,包括该程序订购披萨,...
You invoked undefined behavior by accessing memory you did not allocate. This works purely "by chance". Literally every behavior of you program would be legal, including the program ordering pizza, ...
这在大多数情况下可能会在实践中起作用,因为您的操作系统通常不仅会为您提供4字节或类似的内容,而且会为您提供一整页的内存(通常为4kB),但要强调这一点:您永远无法依靠这种行为!
This will probably work in practice most of the time because your OS will usually not just give you 4 Byte or something like this, but a whole page of memory (often 4kB) but to emphasize this: You can never rely on this behavior!
这篇关于它如何获得比我想要的更多的内存?(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!