Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

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.

Community Additions

ADD
Show:
© 2015 Microsoft