Main Content

ISO/IEC TS 17961 [xfree]

Reallocating or freeing memory that was not dynamically allocated

Description

Rule Definition

Reallocating or freeing memory that was not dynamically allocated.1

Polyspace Implementation

This checker checks for Invalid free of pointer.

Examples

expand all

Issue

Invalid free of pointer occurs when a block of memory released using the free function was not previously allocated using malloc, calloc, or realloc.

Risk

The free function releases a block of memory allocated on the heap. If you try to access a location on the heap that you did not allocate previously, a segmentation fault can occur.

The issue can highlight coding errors. For instance, you perhaps wanted to use the free function or a previous malloc function on a different pointer.

Fix

In most cases, you can fix the issue by removing the free statement. If the pointer is not allocated memory from the heap with malloc or calloc, you do not need to free the pointer. You can simply reuse the pointer as required.

If the issue highlights a coding error such as use of free or malloc on the wrong pointer, correct the error.

If the issue occurs because you use the free function to free memory allocated with the new operator, replace the free function with the delete operator.

Example - Invalid Free of Pointer Error
#include <stdlib.h>

void Assign_Ones(void) 
{
  int p[10];
  for(int i=0;i<10;i++)
     *(p+i)=1; 
 
  free(p);   
  /* Defect: p does not point to dynamically allocated memory */
}

The pointer p is deallocated using the free function. However, p points to a memory location that was not dynamically allocated.

Correction — Remove Pointer Deallocation

If the number of elements of the array p is known at compile time, one possible correction is to remove the deallocation of the pointer p.

#include <stdlib.h>

void Assign_Ones(void)
 {
  int p[10];
  for(int i=0;i<10;i++)
     *(p+i)=1;   
  /* Fix: Remove deallocation of p */
 }
Correction — Introduce Pointer Allocation

If the number of elements of the array p is not known at compile time, one possible correction is to dynamically allocate memory to the array p.

#include <stdlib.h>

void Assign_Ones(int num) 
{
  int *p;
  /* Fix: Allocate memory dynamically to p */
  p=(int*) calloc(10,sizeof(int)); 
  for(int i=0;i<10;i++)
     *(p+i)=1; 
  free(p); 
}

Check Information

Decidability: Undecidable

Version History

Introduced in R2019a


1 Extracts from the standard "ISO/IEC TS 17961 Technical Specification - 2013-11-15" are reproduced with the agreement of AFNOR. Only the original and complete text of the standard, as published by AFNOR Editions - accessible via the website www.boutique.afnor.org - has normative value.