CWE-672

Operation on a Resource after Expiration or Release. [Improper-Control-Of-A-Resource-Through-Its-Lifetime]

Required inputs: IR, StaticSemanticAnalysis

The product uses, accesses, or otherwise operates on a resource after that resource has been expired, released, or revoked.
Demonstrative Examples
Example 1

The following code shows a simple example of a use after free error:

Example Language:C
    char* ptr = (char*)malloc (SIZE);
    if (err) {
        abrt = 1;
        free(ptr);
    }
    ...
    if (abrt) {
        logError("operation aborted before commit", ptr);
    }

When an error occurs, the pointer is immediately freed. However, this pointer is later incorrectly used in the logError function.

Example 2

The following code shows a simple example of a double free error:

Example Language:C
    char* ptr = (char*)malloc (SIZE);
    ...
    if (abrt) {
        free(ptr);
    }
    ...
    free(ptr);

Double free vulnerabilities have two common (and sometimes overlapping) causes:

  • Error conditions and other exceptional circumstances
  • Confusion over which part of the program is responsible for freeing the memory

Although some double free vulnerabilities are not much more complicated than the previous example, most are spread out across hundreds of lines of code or even different files. Programmers seem particularly susceptible to freeing global variables more than once.

Example 3

In the following C/C++ example the method processMessage is used to process a message received in the input array of char arrays. The input message array contains two char arrays: the first is the length of the message and the second is the body of the message. The length of the message is retrieved and used to allocate enough memory for a local char array, messageBody, to be created for the message body. The messageBody is processed in the method processMessageBody that will return an error if an error occurs while processing. If an error occurs then the return result variable is set to indicate an error and the messageBody char array memory is released using the method free and an error message is sent to the logError method.

Example Language:C
    #define FAIL 0
    #define SUCCESS 1
    #define ERROR -1
    #define MAX_MESSAGE_SIZE 32

    int processMessage(char **message)
    {
        int result = SUCCESS;

        int length = getMessageLength(message[0]);
        char *messageBody;

        if ((length > 0) && (length < MAX_MESSAGE_SIZE)) {

            messageBody = (char*)malloc(length*sizeof(char));
            messageBody = &message[1][0];

            int success = processMessageBody(messageBody);

            if (success == ERROR) {
                result = ERROR;
                free(messageBody);
            }
        }
        else {
            printf("Unable to process message; invalid message length");
            result = FAIL;
        }

        if (result == ERROR) {
            logError("Error processing message", messageBody);
        }

        return result;
    }

However, the call to the method logError includes the messageBody after the memory for messageBody has been released using the free method. This can cause unexpected results and may lead to system crashes. A variable should never be used after its memory resources have been released.

Example Language:C
    ...
    messageBody = (char*)malloc(length*sizeof(char));
    messageBody = &message[1][0];

    int success = processMessageBody(messageBody);

    if (success == ERROR) {
        result = ERROR;
        logError("Error processing message", messageBody);
        free(messageBody);
    }
    ...
Excerpts from CWE [https://cwe.mitre.org], Copyright (C) 2006-2026, the MITRE Corporation. See section 9.4. "3rd-Party Licenses" in the documentation for full details.

Possible Messages

Key

Text

Severity

Disabled

double_free

Dynamic memory released here was already released earlier

None

False

invalidated_object

The referenced object “{}” of {} “{}” could be invalid.

None

False

possible_double_free

Dynamic memory released here possibly already released earlier

None

False

possible_use_after_free

Dynamic memory possibly used after it was previously released

None

False

use_after_free

Dynamic memory used after it was previously released

None

False

Options

functions_with_ignored_deallocators

functions_with_ignored_deallocators : set[str] = set()

Set of functions (given by their qualified name) where all deallocators are ignored. For these functions, the check will never report a use-after-free. It will also assume that these functions never create freed pointers, neither by return value, out param, nor by modifying global state.
 

invalidating_function_map

invalidating_function_map

Type: dict[bauhaus.analysis.config.QualifiedName, set[bauhaus.analysis.config.FunctionName]]

Default:

{
   'std::deque': {'clear', 'emplace', 'emplace_back', 'emplace_front', 'erase', 'insert', 'pop_back', 'pop_front', 'push_back', 'push_front', 'remove', 'reserve', 'resize', 'unique'},
   'std::forward_list': {'clear', 'erase', 'erase_after', 'pop_back', 'pop_front', 'remove', 'reserve', 'resize', 'unique'},
   'std::list': {'clear', 'erase', 'pop_back', 'pop_front', 'remove', 'remove_if', 'reserve', 'resize', 'unique'},
   'std::map': {'clear', 'erase'},
   'std::multimap': {'clear', 'erase'},
   'std::multiset': {'clear', 'erase'},
   'std::set': {'clear', 'erase'},
   'std::unordered_map': {'clear', 'emplace', 'erase', 'insert', 'pop_back', 'pop_front', 'rehash', 'remove', 'reserve', 'resize', 'unique'},
   'std::unordered_multimap': {'clear', 'emplace', 'erase', 'insert', 'pop_back', 'pop_front', 'rehash', 'remove', 'reserve', 'resize', 'unique'},
   'std::unordered_multiset': {'clear', 'emplace', 'erase', 'insert', 'pop_back', 'pop_front', 'rehash', 'remove', 'reserve', 'resize', 'unique'},
   'std::unordered_set': {'clear', 'emplace', 'erase', 'insert', 'pop_back', 'pop_front', 'rehash', 'remove', 'reserve', 'resize', 'unique'},
   'std::valarray': {'resize'},
   'std::vector': {'clear', 'emplace', 'emplace_back', 'erase', 'insert', 'pop_back', 'pop_front', 'push_back', 'remove', 'reserve', 'resize', 'unique'}
}
Invalidating (unqualified) methods for the given (qualified) container types. (Some method names may come from super classes of the container type.) If an empty set of invalidating functions is given for a certain type (i.e. 'std::basic_string'), all methods not explicitly given in the option 'non_invalidating_functions' are considered as invalidating.
 

invalidating_only_argument_map

invalidating_only_argument_map

Type: dict[bauhaus.analysis.config.QualifiedName, set[bauhaus.analysis.config.FunctionName]]

Default:

{
   'std::list': {'erase'},
   'std::map': {'erase'},
   'std::multimap': {'erase'},
   'std::multiset': {'erase'},
   'std::set': {'erase'},
   'std::unordered_map': {'erase'},
   'std::unordered_multimap': {'erase'},
   'std::unordered_multiset': {'erase'},
   'std::unordered_set': {'erase'}
}
For functions like "erase" only taking a single iterator argument only this argument iterator is invalided (possibly missing aliases). This avoids false positives for a common pattern where elements are erased in a loop.
 

non_invalidating_functions

non_invalidating_functions : set[bauhaus.analysis.config.FunctionName] = {'at', 'back', 'begin', 'end', 'front', 'operator[]', 'rbegin', 'rend'}

Non-invalidating methods for all container types.
 

report_freed_this_at_call

report_freed_this_at_call : bool = False

This option controls findings when a freed pointer is used in C++ to call a non-static member function. When set to true, the use at the call is directly reported. When false, the analysis waits for an actual dereference (of the this-pointer then) inside the callee, and only reports those.
 

report_read_pointer_args_in_calls_to_undefined

report_read_pointer_args_in_calls_to_undefined : bool = True

Report when freed pointers are passed to undefined (external) functions.
 

resources

resources

Type: set[str]

Default: {'C++ArrayHeapMemory', 'C++HeapMemory', 'CudaAsyncMemory', 'CudaDeviceMemory', 'CudaDriverAsyncMemory', 'CudaHostMemory', 'CudaManagedMemory', 'FileHandle', 'HeapMemory', 'UniquePtrHeapMemory'}

Set of resources to be checked (selection of rules in the Resources group).
 

witness_paths

witness_paths : bool = True

Whether witness paths should be determined and included in the issue.