Is assigning ref of var to a ptr in different scope safe in C++

Viewed 41

I want to know if this is a memory-safe and that if there is a chance the address could be overwritten (dangling ptr)

#include <iostream>

int main() {
  int *ptr;
  std::cout << *ptr << std::endl;
  {  
    int x = 5;
    ptr = &x;
  }
  std::cout << *ptr << std::endl;
  std::cout << ptr << std::endl;
  *ptr = 10;
  std::cout << *ptr << std::endl;
  std::cout << ptr << std::endl;
  std::cout << "Hello, world!";
    return 0;
}

output of code

1 Answers

Pointers point to a location in memory, and that memory location must be available to use otherwise you have undefined behavior. When you write

{  
    int x = 5;
    ptr = &x;
}

you have set the pointer to point to a temporary memory location, which goes out of scope after the block. After this point, you are not allowed to use that memory location as the program is free to use it for something else.

Given this is undefined behavior, anything can happen. If you're lucky it will crash, if you're unlucky it will appear to work and bite your later on.

Related