Skip to content

Latest commit

 

History

History
38 lines (29 loc) · 1.69 KB

c26487.md

File metadata and controls

38 lines (29 loc) · 1.69 KB
title description ms.date ms.topic f1_keywords helpviewer_keywords ms.assetid
C26487
Reference for Visual Studio C++ code analysis warning C26487 from the C++ Core Guidelines.
01/30/2020
conceptual
C26487
C26487
2b0dbec3-c963-4437-8218-933717c1db98

C26487 LIFETIMES_FUNCTION_POSTCONDITION_VIOLATION

Don't allow a function to return an invalid pointer, either through a formal return statement or through output parameters.

int* ex1(int a)
{
  return &a;     // returns a dangling pointer to the stack variable 'a'
}

void ex2(int a, int** out)
{
  *out = &a;    // 'out' contains a dangling pointer to the stack variable 'a'
}

Remarks

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

  • Never dereference an invalid (dangling) or known-null pointer.
  • Never return, either by formal return statement or out parameter, any dangling pointer from a function.
  • Never pass an invalid (dangling) pointer to any function.

An invalid pointer is dangling when it points to something that isn't there anymore. For example, any pointer to a local variable or parameter, once it's gone out of scope. Or, a pointer to a resource that's been deleted. Even a pointer to a static can be dangling, if the value gets changed before it can be used. A dangling pointer was once valid; that's what distinguishes it from other kinds of invalid pointers, such as an uninitialized pointer, or nullptr.

See also