0
#include <iostream>
using namespace std;
int* JustATest()
{
    int x;
    x = 5 + 10;
    return &x;
}
void main()
{
    int * ptr = JustATest(); //return address
    cout << *ptr << endl; //the output is 15
}

the variable x should be destroyed (de-allocated) when the function finish executing then where do the pointer ptr point to exactly in memory ? is the variable x is allocated in the main stackframe pointed to by ptr but its different than the destroyed variable or its the same variable the same memory cell ?

Genarto
  • 3
  • 2

1 Answers1

0

The pointer becomes a stray or dangling pointer, and dereferencing it will lead to undefined behavior.

If your program have UB (Undefined Behavior) it is ill-formed and invalid.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621