Udostępnij za pośrednictwem


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.

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.