Main Content

CWE Rule 911

Improper Update of Reference Count

Since R2026a

Description

The product uses a reference count to manage a resource, but it does not update or incorrectly updates the reference count.

Polyspace Implementation

The rule checker checks for Use of previously freed pointer.

Examples

expand all

Issue

This issue occurs when you access a block of memory after freeing the block using the free function.

Risk

When a pointer is allocated dynamic memory with malloc, calloc or realloc, it points to a memory location on the heap. When you use the free function on this pointer, the associated block of memory is freed for reallocation. Trying to access this block of memory can result in unpredictable behavior or even a segmentation fault.

Fix

The fix depends on the root cause of the defect. See if you intended to free the memory later or allocate another memory block to the pointer before access.

As a good practice, after you free a memory block, assign the corresponding pointer to NULL. Before dereferencing pointers, check them for NULL values and handle the error. In this way, you are protected against accessing a freed block.

Example — Use of Previously Freed Pointer Error

The free statement releases the block of memory that pi refers to. Therefore, dereferencing pi after the free statement is not valid.

#include <stdlib.h>
#include <stdio.h>
 int increment_content_of_address(int base_val, int shift)
   { 
    int j;
    int* pi = (int*)malloc(sizeof(int));
    if (pi == NULL) return 0;

    *pi = base_val;
    free(pi);

    j = *pi + shift; // Noncompliant
 
    return j;
   }
Correction — Free Pointer After Use

One possible correction is to free the pointer pi only after the last instance where it is accessed.

#include <stdlib.h>

int increment_content_of_address(int base_val, int shift)
{
    int j;
    int* pi = (int*)malloc(sizeof(int));
    if (pi == NULL) return 0;

    *pi = base_val;

    j = *pi + shift;
    *pi = 0;

    /* Compliant: The pointer is freed after its last use */
    free(pi);               
    return j;
}

Check Information

Category: Resource Management Errors
PQL Name: std.cwe_native.R911

Version History

Introduced in R2026a