-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
Brian
  • 14,610
  • 7
  • 35
  • 43
ZeRoHuK
  • 13
  • 5
  • 2
    It didn't get more memory than you wanted. You invoked undefined behavior and proceeded to [memory stomp](http://stackoverflow.com/questions/13669329/what-is-a-memory-stomp) by writing to addresses which you did not allocate. – Cory Kramer Oct 14 '14 at 18:57
  • @Cyber: it's entirely possible he got more memory than he wanted, but the undefined behavior/memory stomp still applies. – Mooing Duck Oct 14 '14 at 18:59
  • 1
    You have [*undefined behavior*](http://en.wikipedia.org/wiki/Undefined_behavior), because you write and read out of bounds of the memory you allocate, that means your whole program is invalid. – Some programmer dude Oct 14 '14 at 18:59
  • Thanks for answering in advance @Cyber.But does it happen all the time? – ZeRoHuK Oct 14 '14 at 19:03
  • @ZeRoHuK - `But does it happen all the time?` Does *what* happen all the time? – PaulMcKenzie Oct 14 '14 at 19:08
  • ***But does it happen all the time?*** No it does not. You can not rely on undefined behavior to help you. Baum mit Augen explained that. – drescherjm Oct 14 '14 at 19:23

2 Answers2

4

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!

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
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.

Jared Wadsworth
  • 839
  • 6
  • 15