Versions Compared

Key

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

...

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
 
int f(size_t n) {
  int error_condition = 0;

  int *x = (int *)malloc(n * sizeof(int));
  if (x == NULL)
    return -1;

  /* Use x and set error_condition on error. */

  if (error_condition == 1) {
    /* Handle error condition*/
    free(x);
  }

  /* ... */
  free(x);
  return error_condition;
}

...

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
int f(size_t n) {
  int error_condition = 0;

  if (n > SIZE_MAX / sizeof(int)) {
    errno = EOVERFLOW;
    return -1;
  }

  int *x = (int*)malloc(n * sizeof(int));
  if (x == NULL) {
    /* Report allocation failure to caller. */
    return -1;
  }

  /* Use x and set error_condition on error. */

  if (error_condition != 0) {
    /* Handle error condition and proceed. */
  }

  free(x);

  return error_condition;
}

...

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
 
/* p is a pointer to dynamically allocated memory. */
void func(void *p, size_t size) {

  p2 = realloc(p, size);
  if (p2 == NULL) {
  free(p);  /* p may be indeterminate when (size == 0). */ 
    free(p); 
    return;
  }
}

Section Subclause 7.22.3 of the C Standard [ISO/IEC 9899:2011] states:

...

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
/* p is a pointer to dynamically allocated memory. */
void func(void *p, size_t size) {
  if (size) {
    p2 = realloc(p, size);
    if (p2 == NULL) {
      free(p);
      return;
    }
  }
 else {
    free(p);
    return;
  }
}

Exception

MEM31-EX1: Some library implementations accept and ignore a deallocation of already-free memory. If all libraries used by a project have been validated as having this behavior, then this rule can be ignored.

...

Bibliography

[ISO/IEC 9899:2011]Section Subclause 7.22.3, "Memory Management Functions"
Annex J, J.2, "Undefined behavior"
[MIT 2005] 
[OWASP Double Free]"Double Free"
[Viega 2005]"Doubly Freeing Memory"
[VU#623332] 

...