Before the lifetime of the last pointer object that stores the return value of a call to a standard memory allocation function has ended, it must be matched by a call to a standard memory deallocation function free()
with that pointer value.
Noncompliant Code Example
In this noncompliant example, the object allocated by the call to malloc()
is not freed before the end of the lifetime of the last pointer object (text_buffer
) referring to the object:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> constenum size_t{ BUFFER_SIZE = 32 }; int f(void) { char *text_buffer = (char *)malloc(BUFFER_SIZE); if (text_buffer == NULL) { return -1; } return 0; } |
Compliant Solution
...
In this compliant solution, the pointer is deallocated with a call to free()
:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> constenum size_t{ BUFFER_SIZE = 32 }; int f(void) { char *text_buffer = (char *)malloc(BUFFER_SIZE); if (text_buffer == NULL) { return -1; } free(text_buffer); return 0; } |
...
MEM31-EX1: Allocated memory does not need to be freed if it is used throughout the lifetime of the assigned to a pointer with static storage duration whose lifetime is the entire execution of a program. The following code example illustrates a pointer object that stores the return value from malloc()
that is stored in a static
variable:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> constenum size_t{ BUFFER_SIZE = 32 }; int f(void) { static char *text_buffer = NULL; if (text_buffer == NULL) { text_buffer = (char *)malloc(BUFFER_SIZE); if (text_buffer == NULL) { return -1; } } return 0; } |
...
CERT C++ Secure Coding Standard | MEM31-CPP. Free dynamically allocated memory exactly once |
ISO/IEC TR 24772:2013 | Memory Leak [XYL] |
ISO/IEC TS 17961 | Failing to close files or free dynamic memory when they are no longer needed [fileclose] |
MITRE CWE | CWE-401, Failure to Improper Release of Memory Before Removing Last Reference ('"Memory Leak'") |
Bibliography
[ISO/IEC 9899:2011] | Subclause 7.22.3, "Memory Management Functions" |
...