Warning C26489

Don't dereference a pointer that may be invalid.

int ex1()
    int* px;

        int x = 0;
        px = &x;

    return *px;   // 'px' was invalidated when 'x' went out of scope.


The Lifetime guidelines from the C++ core guidelines outline a contract that code can follow which will enable more thorough static memory leak and dangling pointer detection. The basic ideas behind the guidelines are:

  1. Never dereference an invalid (dangling) or known-null pointer
  2. Never return (either formal return or out parameter) any pointer from a function.
  3. Never pass an invalid (dangling) pointer to any function.

See also

C++ Core Guidelines Lifetimes Paper