Edit

Share via


Warning C6308

'realloc' may return null pointer: assigning a null pointer to 'parameter-name', which is passed as an argument to 'realloc', will cause the original memory block to be leaked

Remarks

Heap reallocation functions don't free the passed buffer if reallocation is unsuccessful, potentially resulting in a memory leak if not handled properly. To correct the issue, assign the result of the reallocation function to a temporary variable, and then replace the original pointer after successful reallocation.

Code analysis name: REALLOCLEAK

Example

The following sample code generates warning C6308. This issue stems from the assignment of the return value from realloc to x. If realloc fails and returns a null pointer, then the original memory pointed to by x won't be freed:

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

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

To resolve the issue, you can create a temporary variable to store the return value of realloc. This change allows you to free the previously allocated memory safely if realloc fails:

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

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

This warning might generate noise if there's 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 issues altogether, use the mechanisms that are provided by the C++ Standard Library (STL). These include shared_ptr, unique_ptr, and containers such as vector. For more information, see Smart pointers and C++ Standard Library.

See also

Warning C6014