Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
 
const size_t BUFFER_SIZE = 32;

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

...

In this compliant solution, the pointer is deallocated with a call to free():

Code Block
bgColor#ccccff
langc
#include <stdlib.h>

const size_t BUFFER_SIZE = 32;

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

...

MEM31-EX1: Allocated memory does not need to be freed if it is used throughout the lifetime of the program. The following code example illustrates a pointer object that stores the return value from malloc() that is stored in a static variable.:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
const size_t BUFFER_SIZE = 32;

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

...

Failing to free memory can result in the exhaustion of system memory resources, which can lead to a denial-of-service attack.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM31-C

Medium

Probable

Medium

P8

L2

...