I have this very simple code:

#include <iostream>
using namespace std;

int main()
{
    int *p, *q, u;
    
    {
        p = new int(4);
        int v = 5;
        q = &v;
        u= v;
    }//End scope 2
    
    cout<< *p << "\n" << *q << "\n" << u;
    delete p;

    return 0;
}

And the output is:

4
5
5

Pleaso cerrect me if I'm wrong :) ...

  • if I understand, p is pointing to a memory space that was allocated in the heap, this memory won't be affecetd at the "end scope" and will only be dellocated when calling delete.
  • Then u is a hard copy of v, so there's actually a copy of it's value somewhere else in the stack memory.
  • On the other hand q points to the address of v, which is allocated in the stack and should be erased (?) when leaving the "scope 2", if this is the case, why printing *q still finds the right value of v?

why printing *q still finds the right value of v?

There is no such thing as "right value" for an object that no longer exists.

You observed the behaviour that you did because the behaviour of the program is undefined. You observed one behaviour; the behaviour could have been something else because the language doesn't guarantee this behaviour, but the behaviour wasn't something else because the language doesn't guarantee any other behaviour either.

The behaviour could be any of these:

  • Expected
  • Unexpected
  • Something that you consider "right"
  • Something that you consider "wrong"
  • Always the same behaviour
  • Never the same behaviour
  • Seemingly deterministic
  • Nondeterministic
  • Random
  • Not random
  • Always the correct behaviour that you want, except when you deploy it into production and take a vacation
  • Anything that wasn't listed above

It's undefined behavior. When the code exits a scope, the data and variables in the scope are deleted. But that does not mean the memory space in RAM is completely erased. The compiler de-allocates that memory so that the memory can be used again but the last data just remains there. So, if the memory is not allocated to something else (not necessarily your program), it will still retain the last data. In practice, this rarely happens. But for small snippets like your code, since the memory data is printed almost immediately after de-allocation, it might show the correct data.