...
Code Block | ||||
---|---|---|---|---|
| ||||
#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 | ||||
---|---|---|---|---|
| ||||
#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 | ||||
---|---|---|---|---|
| ||||
#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 | ||||
---|---|---|---|---|
| ||||
#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.
...
CERT C Secure Coding Standard | MEM04-C. Do not perform zero-length allocations INT32-C. Ensure that operations on signed integers do not result in overflow |
CERT C++ Secure Coding Standard | MEM31-CPP. Free dynamically allocated memory exactly once |
ISO/IEC TR 24772:2013 | Dangling Reference to Heap [XYK] Memory Leak [XYL] |
ISO/IEC TS 17961 (Draft) | Freeing memory multiple times [dblfree] |
MITRE CWE | CWE-415, Double free |
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] |
...