Main Content

Missing reset of freed pointer

Pointer free not followed by a reset statement to clear leftover data

Description

This defect occurs when a pointer is freed and not reassigned another value. After freeing a pointer, the memory data is still accessible. To clear this data, the pointer must also be set to NULL or another value.

Risk

Not resetting pointers can cause dangling pointers. Dangling pointers can cause:

  • Freeing already freed memory.

  • Reading from or writing to already freed memory.

  • Hackers executing code stored in freed pointers or with vulnerable permissions.

Fix

After freeing a pointer, if it is not immediately assigned to another valid address, set the pointer to NULL.

Examples

expand all

#include <stdlib.h>
enum {
    SIZE3   = 3,
    SIZE20  = 20
};

void allocateAndFreeMemory()
{
    static char *str = NULL;

    if (str == NULL)
        str = (char *)malloc(SIZE20);

    if (str != NULL)
        free(str);
}

In this example, the pointer str is freed at the end of the program. The next call to allocateAndFreeMemory can fail because str is not NULL and the initialization to NULL can be invalid.

Correction — Redefine free to Free and Reset

One possible correction is to customize free so that when you free a pointer, it is automatically reset.

#include <stdlib.h>
enum {
    SIZE3   = 3,
    SIZE20  = 20
};

static void sanitize_free(void **p)
{
    if ((p != NULL) && (*p != NULL))
    {
        free(*p);
        *p = NULL;
    }
}

#define free(X) sanitize_free((void **)&X)

void allocateAndFreeMemory()
{
    static char *str = NULL;

    if (str == NULL)
        str = (char *)malloc(SIZE20);

    if (str != ((void *)0))
    {
        free(str);
    }
}

Result Information

Group: Good Practice
Language: C | C++
Default: Off
Command-Line Syntax: MISSING_FREED_PTR_RESET
Impact: Low

Version History

Introduced in R2016b