Beginner's question: Pointers and scope of variables

closed account (z1vC5Di1)
Hello everybody,
I wonder if this is something you are allowed to do in C++:
1
2
3
4
5
6
7
8
9
{
 int *x;
 {
  int y = 10;
  x = &y;
 }
 ...
 cout << *x;
}

My concern: As far as I understand the concept of a stack memory, I always thought that during runtime a backtracking point is set every time a new scope is entered and that this backtracking point somewhat marks the "furthest" address in memory which is currently in use and which must therefore not be (re-)allocated.

Thus I thought - after leaving the inner scope in the above example - that the address in the stack for y might be reallocated somewhere in a possible later codeline (indicated by "...", maybe another variable). Thus the value 10 which is referenced by the pointer x might be altered, after the address of y was somewhat "set free" (after the scope, in which the variable y was declared, ends) and reasigned.

I hope I was able to express what I was wondering about. Am I thinking right here or is the C++ compiler or preprocessor taking care of that problem? Or is my understanding of a stack memory simply wrong?

Thank your for your help and explanations! Best, Rafael
Last edited on
Your understanding is correct: the object y is destroyed at line 6. The expression *x at line 8 invokes undefined behavior.

Faced with a program that has undefined behavior, the compiler may do anything. It may cache the value 10 and print that regardless of what happens at line 7, or it may actually read from the memory location once occupied by y, in which case the contents of line 7 would affect the results.

Undefined behavior is something that you're "allowed" to do in C++, but the results of doing so are unpredictable.
Topic archived. No new replies allowed.