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

2019-03-07 07:39发布

问题:

This question already has an answer here:

  • Why doesn't my program crash when I write past the end of an array? 9 answers

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.