Share via


C6308

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

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.

Example

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 and C++ Standard Library.

See Also

C6014