You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 130 Next »

Before the lifetime of the last pointer object that stores the return value of a call to a standard memory allocation function has ended, it must be matched by a call to a standard memory deallocation function with that pointer value.

Noncompliant Code Example

In this noncompliant example, the object allocated by the call to malloc() is not freed before the end of the lifetime of last pointer object (text_buffer) referring to the object.

#include <stdlib.h>
 
int f(void) {
  char *text_buffer = (char *)malloc(BUFSIZ); 
  if (text_buffer == NULL) {
    return -1;
  }
  return 0;
}

Compliant Solution 

In this compliant solution, the pointer object that stores the return value from malloc() is stored in a variable of static storage duration.

#include <stdlib.h>

char *text_buffer;
 
int f(void) {
  text_buffer = (char *)malloc(BUFSIZ); 
  if (text_buffer == NULL) {
    return -1;
  }
  return 0;
}

Risk Assessment

Freeing memory multiple times can result in an attacker executing arbitrary code with the permissions of the vulnerable process.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM31-C

High

Probable

Medium

P12

L1

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

Coverity

2017.07

RESOURCE_LEAK

Finds resource leaks from variables that go out of scope while owning a resource

Fortify SCA

5.0

  

Klocwork

2024.3

MLK
UFM.FFM

 

LDRA tool suite

9.7.1

484 S

Fully implemented

Splint

3.1.1  

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding StandardMEM31-CPP. Free dynamically allocated memory exactly once
ISO/IEC TR 24772:2013Memory Leak [XYL]
ISO/IEC TS 17961Failing to close files or free dynamic memory when they are no longer needed [fileclose]
MITRE CWE

CWE-401, Failure to Release Memory Before Removing Last Reference ('Memory Leak')

Bibliography

[ISO/IEC 9899:2011]Subclause 7.22.3, "Memory Management Functions"

 


  • No labels