0

here is my code

#include<iostream>

using namespace std;

int *f1(int x) {
    return &x;
}

void f2(int a, int b, int c){

    cout<<a<<endl;
}

int main() {

    cout<<"hari Hari"<<endl;

    int *x;
    x = f1(90);
    f2(3,45,2);

    cout<<*x<<endl;

    system("PAUSE");
}

now as f1 return pointer to stack, which was suppose to overwritten by f2, and expected output should be looks something like this " hari Hari 3 3 " but actually I get right answer, and my actual output is, " hari Hari 3 90 " I can't understand why it is not overwrite the value of f1 function's 'x'.

Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76
dplank
  • 91
  • 8

1 Answers1

3

You're relying on undefined behavior, which means you can't rely on it behaving in any particular way. In your case, you just got "lucky".

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • But as I know stack allocations are contiguous, that is laid out end-to-end, and heap allocations are not necessarily contiguous so can you please give some idea of memory model which it manage here. – dplank Feb 21 '15 at 06:46
  • You could print out the addresses & see for yourself. – Scott Hunter Feb 21 '15 at 13:04