Versions Compared

Key

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

...

This compliant solution eliminates the possibility of str, referencing nondynamic memory when it is supplied to free().:

Code Block
bgColor#ccccff
langc
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;
}

...

In this noncompliant example, the pointer parameter to realloc(), buf, does not refer to dynamically allocated memory.:

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

...

In this compliant solution, buf refers to dynamically allocated memory.:

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

...

MEM34-EX1: Some library implementations accept and ignore a deallocation of non-allocated 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.

...

Tool

Version

Checker

Description

Compass/ROSE

  

Can detect some violations of this rule.

Coverity

Include Page
Coverity_V
Coverity_V

BAD_FREE

Identifies calls to free() where the argument is a pointer to a function or an array. It also detects the cases where Free is used on an address-of expression, which can never be heap allocated. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary.

Klocwork

Include Page
Klocwork_V
Klocwork_V

FNH.MIGHT
FNH.MUST
FUM.GEN.MIGHT
FUM.GEN.MUST

 

LDRA tool suite

Include Page
LDRA_V
LDRA_V

483 S

Fully implemented.

Related Vulnerabilities

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

...