Warning C6011

Dereferencing NULL pointer 'pointer-name'.

Remarks

This warning indicates that your code dereferences a potentially null pointer. If the pointer value is invalid, the result is undefined. To resolve the issue, validate the pointer before use.

Code analysis name: DEREF_NULL_PTR

Example

The following code generates this warning because a call to malloc might return null if insufficient memory is available:

#include <malloc.h>

void f( )
{
  char *p = ( char * ) malloc( 10 );
  *p = '\0';

  // code ...
 free( p );
}

To correct this warning, examine the pointer for a null value as shown in the following code:

#include <malloc.h>
void f( )
{
  char *p = ( char * )malloc ( 10 );
  if ( p )
  {
    *p = '\0';
    // code ...

    free( p );
  }
}

Functions may have parameters annotated by using the Null property in a Pre condition. Allocate memory inside these functions before you dereference the parameter. The following code generates warning C6011 because an attempt is made to dereference a null pointer (pc) inside the function without first allocating memory:

#include <sal.h>
using namespace vc_attributes;
void f([Pre(Null=Yes)] char* pc)
{
  *pc='\0'; // warning C6011 - pc is null
  // code ...
}

The careless use of malloc and free leads to memory leaks and exceptions. To minimize these kinds of leaks and exception problems altogether, avoid allocating raw memory yourself. Instead, use the mechanisms provided by the C++ Standard Library (STL). These include shared_ptr, unique_ptr, and vector. For more information, see Smart Pointers and C++ Standard Library.

Heuristics

A heuristic used to reduce the number of warnings in legacy code assumes that a pointer is non-NULL unless there is evidence that it is NULL. In the examples we've seen so far, pointers returned by malloc or new might be NULL because allocation might fail. Another characteristic that the analysis engine uses as evidence of nullability is if the program explicitly checks for NULL. This is illustrated in the following examples:

void f(int* n)
{
  *n = 1; // Does not warn, n is assumed to be non-null
}

void f(int* n)
{
  if (n) {
    (*n)++;
  }
  *n = 1; // Warns because the earlier conditional shows that n might be null
}

In the second case, the user can fix the warning by moving the *n = 1 line inside the if block.

See also