Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
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 allocation error */
    }
    strcpy(str, argv[1]);
  }
  else {
    str = "usage: $>a.exe [string]";
    printf("%s\n", str);
  }
  /* ... */
  free(str);
  return 0;
}

Compliant Solution

This compliant solution eliminates the possibility of str, referencing nondynamic non-dynamic memory when it is supplied 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 allocation error */
    }
    strcpy(str, argv[1]);
  }
  else {
    printf("%s\n", "usage: $>a.exe [string]");
    return -1;
  }
  /* ... */
  free(str);
  return 0;
}

Noncompliant Code Example (realloc())

...

Code Block
bgColor#FFcccc
langc
#define#include <stdlib.h>
 
enum { BUFSIZE = 256 };
 
void f(void) {
  char buf[BUFSIZE];
  char *p;
  /* ... */
  p = (char *)realloc(buf, 2 * BUFSIZE);  /* violation */
  /* ... */
}

Compliant Solution(realloc())

...

Code Block
bgColor#ccccff
langc
#define#include <stdlib.h>
 
enum { BUFSIZE = 256 };
 
void f(void) {
  char *buf = (char *)malloc(BUFSIZE * sizeof(char));
  char *p;
  /* ... */
  p = (char *)realloc(buf, 2 * BUFSIZE);  /* violation */
  /* ... */
}

Exceptions

MEM34-EX1: Some library implementations accept and ignore a deallocation of nonallocated memory (or, alternatively, cause a runtime-constraint violation). If all libraries used by a project have been validated as having this behavior, then this rule can be ignored.

...

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

Related Guidelines

...

[Seacord 2013]Chapter 4, "Dynamic Memory Management"
[ISO/IEC 9899:2011]Annex J, subclause J.2, "Undefined behavior"

 

...