Export (0) Print
Expand All
Expand Minimize

C6308

warning C6308: 'realloc' may return null pointer: assigning a null pointer to <variable>, which is passed as an argument to 'realloc', will cause the original memory block to be leaked

This warning indicates a memory leak that is the result of the incorrect use of a reallocation function. Heap reallocation functions do not free the passed buffer if reallocation is unsuccessful. To correct the defect, assign the result of the reallocation function to a temporary, and then replace the original pointer after successful reallocation.

The following sample code generates this warning:

#include <malloc.h>
#include <windows.h>

void f( )
{
  char *x;
  x = (char *) malloc(10);
  if (x != NULL)
  {
    x = (char *) realloc(x, 512);
    // code...
    free(x);
  }   
}

To correct this warning, use the following code:

#include <malloc.h>
#include <windows.h>

void f()
{
  char *x, *tmp;

  x = (char *) malloc(10);

  if (x != NULL)
  {
    tmp = (char *) realloc(x,512);
    if (tmp != NULL) 
    {
      x = tmp;
    }
    free(x);
  }
}

This warning might generate noise if there is a live alias to the buffer-to-be-reallocated at the time of the assignment of the result of the reallocation function.

To avoid these kinds of problems altogether, use the mechanisms that are provided by the C++ Standard Template Library (STL). These include shared_ptr, unique_ptr, and vector. For more information, see Smart Pointers (Modern C++) and Standard C++ Library Reference.

Show:
© 2014 Microsoft