-4

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
6
  • 2
    It didn't get more memory than you wanted. You invoked undefined behavior and proceeded to memory stomp by writing to addresses which you did not allocate. Commented Oct 14, 2014 at 18:57
  • @Cyber: it's entirely possible he got more memory than he wanted, but the undefined behavior/memory stomp still applies. Commented Oct 14, 2014 at 18:59
  • 1
    You have undefined behavior, because you write and read out of bounds of the memory you allocate, that means your whole program is invalid. Commented Oct 14, 2014 at 18:59
  • Thanks for answering in advance @Cyber.But does it happen all the time? Commented Oct 14, 2014 at 19:03
  • @ZeRoHuK - But does it happen all the time? Does what happen all the time? Commented Oct 14, 2014 at 19:08

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.