Search code examples
c++gccdangling-pointer

Why I don't get a dangling pointer?


Why I is the output of the following code 10 and not an error? Isn't object2 a dangling pointer?

#include <iostream>
using namespace std;


int *method()
{
  int object = 10;
  return &object;
}


int main()
{
    int *object2 = method();

    cout << *object2;
}

Thanks!


Solution

  • Why I is the output of the following code 10 and not an error?

    Because undefined behaviour is undefined. Specifically, nothing happens to overwrite the memory that used to contain object, so the value hasn't changed by the time you dereference the dangling pointer. If you try printing it a second time, you might see something different. Or not - undefined behaviour could do anything.

    Isn't object2 a dangling pointer?

    Yes. Dereferencing a dangling (or otherwise invalid) pointer gives undefined behaviour, so don't do that.

    You should be able to avoid this by enabling compiler warnings; on GCC, the specific warning is enabled by -Wreturn-local-addr, but I strongly suggest you build with at least -Wall -Wextra -Werror to catch as many potential mistakes as possible.