-3
#include <iostream>

int* dont() {
    int num = 10;
    int* num_ptr = &num;
    return num_ptr;
}

int main() {
    int* a = nullptr;
    a = dont();
    std::cout << *a;
}

This is my code sample. I think 'a' would have garbage value, but memory is still alive. I cannot understand what it is, please help me ! (I use visual studio 2022 for my IDE)

  • precisely what i want to know is pointer 'a' must be dangling pointer. But it wasnt. I cannot understand this situation..
Chris
  • 26,361
  • 5
  • 21
  • 42
  • https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Aug 27 '23 at 01:50
  • 1
    It's undefined behaviour. Undefined behaviour means that the C++ standard does not impose any requirements or constraints on what happens. Beginners (and a few too many self-claimed experienced developers) seem to incorrectly equate undefined behaviour with "will crash" or "will produce garbage output" as if one or both of those are laws of nature. Both of those outcomes are *possible*. But, "will not crash", "will not produce garbage output" are *equally possible* outcomes. – Peter Aug 27 '23 at 02:11
  • 1
    "I bought a rope that the manufacturer says can hold 500 pounds. I tied 600 pounds to the rope, and the rope didn't break. Why?" -- This is basically what you are asking -- maybe the rope won't break, maybe the next rope rated for 500 pounds will break, you don't know. Once you break the rules by tying too much to the rope, then anything can happen -- that is essentially what undefined behavior is about. – PaulMcKenzie Aug 27 '23 at 03:14
  • @user - Nothing says that an `int` that goes out of scope has to go away *immediately*. The rules say that you are not allowed to read it, so we cannot know for sure. – BoP Aug 27 '23 at 09:51
  • If you want `a` to contain garbage value, you'll need to set `a` to that garbage value. Otherwise, `10` is a perfectly cromulent garbage value. – Eljay Aug 27 '23 at 16:51

1 Answers1

2

Returning a pointer to a local variable and then dereferencing that pointer invoke undefined behavior. Anything can happen, but that doesn't mean you necessarily get a garbage value. The program can "work" as an option.

The likelihood of this option is increased in this case as no other functions are called in the interim, reducing the odds that the memory location you're accessing has been overwritten.

Chris
  • 26,361
  • 5
  • 21
  • 42