Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits; reviewed

As noted under undefined Undefined behavior 179, states that the behavior of a program is undefined when

...

Freeing memory that is not allocated dynamically can lead to result in heap corruption and other serious errors similar to those discussed in MEM31-C. Free dynamically allocated memory when no longer needed. The consequences of this error depend on the implementation, but they range from nothing to abnormal program termination. Regardless of the implementation, do . Do not call free() on anything other than a pointer returned by a dynamic memory allocation function, such as malloc(), calloc(), realloc(), or aligned_alloc().

...

This rule does not apply to null pointers. The standard officially declares that when given C Standard guarantees that if free() is passed a null pointer, free() does nothingno action occurs.

Noncompliant Code Example

...

This compliant solution eliminates the possibility of str, referencing nondynamic memory when it is supplied referencing memory that is not allocated dynamically when passed to free():

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
#include <string.h>
 
enum { MAX_ALLOCATION = 1000 };

int main(int argc, const char *argv[]) {
  char *str = NULL;
  size_t len;

  if (argc == 2) {
    len = strlen(argv[1]) + 1;
    if (len > MAX_ALLOCATION) {
      /* Handle error */
    }
    str = (char *)malloc(len);
    if (str == NULL) {
      /* Handle error */
    }
    strcpy(str, argv[1]);
  } else {
    printf("%s\n", "usage: $>a.exe [string]");
    return -1;
  }
  free(str);
  return 0;
}

...

Note that realloc() will behave properly even if malloc() failed, because when given a null pointer, realloc() behaves like a call to malloc().

Risk Assessment

Freeing or reallocating memory that was not dynamically allocated can lead The consequences of this error depend on the implementation, but they range from nothing to arbitrary code execution if that memory is reused by malloc(). 

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM34-C

High

Likely

Medium

P18

L1

...

...