1601
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:
This code attempts to tokenize a string and place it into an array using the strsep function, which
inserts a \0 byte in place of whitespace or a tab character. After finishing the loop, each string in the
AP array points to a location within the input string.
Example Language: C (Bad)
char **ap, *argv[10], *inputstring;
for (ap = argv; (*ap = strsep(&inputstring, " \t")) != NULL;)
if (**ap != '\0')
if (++ap >= &argv[10])
break;
/.../
free(ap[4]);
Since strsep is not allocating any new memory, freeing an element in the middle of the array is
equivalent to free a pointer in the middle of inputstring.
Example 2:
This example allocates a BarObj object using the new operator in C++, however, the programmer
then deallocates the object using free(), which may lead to unexpected behavior.
Example Language: C++ (Bad)
void foo(){
BarObj *ptr = new BarObj()
/* do some work with ptr here */
...
free(ptr);
}
Instead, the programmer should have either created the object with one of the malloc family
functions, or else deleted the object with the delete operator.
Example Language: C++ (Good)
void foo(){
BarObj *ptr = new BarObj()
/* do some work with ptr here */
...
delete ptr;
}
Example 3:
In this example, the programmer dynamically allocates a buffer to hold a string and then searches
for a specific character. After completing the search, the programmer attempts to release the
allocated memory and return SUCCESS or FAILURE to the caller. Note: for simplification, this
example uses a hard-coded "Search Me!" string and a constant string length of 20.
CWE Version 4.14
CWE-763: Release of Invalid Pointer or Reference
CWE-763: Release of Invalid Pointer or Reference