-1

Is there any thing wrong in the following code?

#include <iostream>

using namespace std;

int* pointer;

void assign() {
    int a = 2;
    pointer = &a;
}

int main() {
    assign();
    cout<<*pointer<<endl;
}

According to my knowledge, 'a' exists in stack memory when executing assign(). Hence, after function assign() runs, the memory allocated to 'a' should be released. But in assign(), the address of 'a' is allocated to 'pointer' which exists in data segment. 'pointer' exits in the whole life of this program.

But after assign(), we print out *pointer whose corresponding variable has been released before. Is there any thing wrong will happen? Or is it a undefined behavior?

In fact, the above program can run correctly to print out the right value.

Wei Qiao
  • 1
  • 2
  • Your question is self-contradictory. First you explain why you would not expect correct operation to consist of outputting 2. But then you claim that it is. Which is it? (Hint: The first part is right. The second part is wrong.) – David Schwartz Jul 30 '15 at 01:57
  • `a` no longer exists when `}` is reached at the end of `assign`. At that stage, `pointer` turns into an uninitialized variable. – M.M Jul 30 '15 at 01:58
  • Thank you, guys. I know that a local variable can not exist outside its scope. I meant that the above program can still output the right value. I was not sure why until you told me that it is a undefined behavior and pointer will turn into an uninitialized variable. – Wei Qiao Jul 30 '15 at 16:50

2 Answers2

3

Yes, this is undefined behavior.

The only reason that you "correctly print out the right value" is that because on most common architectures, the formerly vacated address on the stack where the variable existed does not get overwritten or scribbled over by the remaining code in main() that gets executed here.

The code in main() would typically dereference the pointed to the address on the stack before constructing the stack frame for the operator<<() function call.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

You get a correct value because the CPU does not yet use the location of variable (a). But if before you print the pointer the CPU need the location of the variable (a), you well get a wrong value.

Ahmed Shamel
  • 1,982
  • 3
  • 24
  • 58