-1

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

cjde
  • 11
  • 2
  • 6
    This is a textbook [dangling pointer](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer). `ptr` points to `x`, a variable whose lifetime ended when the block it existed in exited. All the dereferences of `ptr` outside that block invoke undefined behavior. – Nathan Pierson Sep 23 '22 at 05:45
  • https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Sep 23 '22 at 05:55
  • 2
    And the first dereference before the block also causes undefined behavior for slightly different reason: Because `ptr` was not initialized or assigned a value it has an indeterminate value which may not be read and certainly not dereferenced. All in all: There are no guarantees that this will compile and if it does compile there are no guarantees that it will behave in any particular way. – user17732522 Sep 23 '22 at 06:23

1 Answers1

1

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.

Matt Cummins
  • 309
  • 5