1328
Phase: Architecture and Design
Strategy = Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides
constructs that make this weakness easier to avoid. For example, glibc in Linux provides
protection against free of invalid pointers.
Phase: Architecture and Design
Use a language that provides abstractions for memory allocation and deallocation.
Phase: Testing
Use a tool that dynamically detects memory management problems, such as valgrind.
Demonstrative Examples
Example 1:
In this example, an array of record_t structs, bar, is allocated automatically on the stack as a local
variable and the programmer attempts to call free() on the array. The consequences will vary based
on the implementation of free(), but it will not succeed in deallocating the memory.
Example Language: C (Bad)
void foo(){
record_t bar[MAX_SIZE];
/* do something interesting with bar */
...
free(bar);
}
This example shows the array allocated globally, as part of the data segment of memory and the
programmer attempts to call free() on the array.
Example Language: C (Bad)
record_t bar[MAX_SIZE]; //Global var
void foo(){
/* do something interesting with bar */
...
free(bar);
}
Instead, if the programmer wanted to dynamically manage the memory, malloc() or calloc() should
have been used.
Example Language: (Good)
void foo(){
record_t *bar = (record_t*)malloc(MAX_SIZE*sizeof(record_t));
/* do something interesting with bar */
...
free(bar);
}
Additionally, you can pass global variables to free() when they are pointers to dynamically allocated
memory.
Example Language: (Good)
record_t *bar; //Global var
void foo(){
bar = (record_t*)malloc(MAX_SIZE*sizeof(record_t));
/* do something interesting with bar */
CWE Version 4.14
CWE-591: Sensitive Data Storage in Improperly Locked Memory
CWE-591: Sensitive Data Storage in Improperly Locked Memory