How could it get more memory than I wanted?(C++) [duplicate]

£可爱£侵袭症+ 提交于 2019-12-03 01:21:51

问题


I wanted to take a 1 integer memory, but how this program can work?

Code:

#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;
}

Input:

999999
999998
999997
999996
999995

Output:

999999
999998
999997
999996
999995

回答1:


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, ...

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!




回答2:


The way that a c++ program uses an array is that it the index that you want, multiplies it by the size of the element the array is made of, then adds it to the first memory location in the array. It just so happened that where you placed this in your program, going back an additional 4 elements didn't corrupt anything, so you were just fine. It doesn't actually care. However if you overwrite another variable, or a stack pointer, then you run into trouble. I wouldn't recommend doing this in practice, however, as the behavior can be undefined.



来源:https://stackoverflow.com/questions/26368244/how-could-it-get-more-memory-than-i-wantedc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!