Share via


6011 - Dereferencing NULL pointer <pointer>

A NULL pointer is being dereferenced. If the pointer value is invalid, the result is undefined.

For an example, see Example 1: Uninitialized Variables and NULL Pointers.

Example

The following code elicits this warning because a call to malloc returns NULL if sufficient memory is not available:

#include <malloc.h>

void f( )
{ 
  char *p = ( char * ) malloc( 10 );
  *p = '\0';
 
  // code ...
  free( p );
}

To avoid 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 );
  }
}

Warning Details

This warning often occurs in situations similar to the ones that generate Warning 6001, except that the pointer has been initialized to NULL.

This warning occurs frequently, but it is risky to assume that it is a false-positive error. Sometimes, this warning identifies a pointer that the programmer believes cannot be NULL when it is dereferenced, but the code is subtly incorrect.

For example:

An allocation fails. Subsequent cleanup code, typically in a distant part of the function, references the NULL pointer while cleaning up from a more likely error.

A pointer and the pointed-to data are both checked for NULL correctly, but a debug/warning message that is printed uses the pointer that might be NULL, as shown in the following example:

For example if varA is NULL:

if (NULL == varA || NULL == varA->part1)
    printf("Bad arg varA or varA->part1 %p %p\n", 
 varA, varA->part1);  // references NULL varA

PREfast for Drivers often generates this warning when the code is checking an argument that is passed to a function to determine if it has a NULL value. Therefore, code that is written like the following example often causes false-positive warnings:

if (NULL == argn)
   functionThatReportsButDoesNotReturn();
x(argn->varA);  // reports accessing a NULL

Although this warning is prone to false-positive results, many of the valid errors that it found were those that are not detected in unit tests. Many of these failures were associated with fail-soft or debugging code that still inadvertently referenced the NULL pointer.

 

 

Send comments about this topic to Microsoft

Build date: 5/3/2011