A program will crash if memory is requested while the heap is exhausted. This error can be generated due to the following possible reasons:
- A memory leak
- An infinite loop
- The program requires more memory than is present by default in the heap
- Incorrect implementation of common data structures (hash tables, vectors, etc.)
If malloc()
is unable to return the requested memory, it returns NULL
instead.
Noncompliant Code Example
This example places no upper bound on the memory space required due to which the program can easily exhaust the heap.
A heap error will be generated if the heap continues to be populated even if there is no space available.
#include <stdio.h> #include <string.h> #include <stdlib.h> enum {MAX_LENGTH=100}; typedef struct namelist_s { char name[MAX_LENGTH]; struct namelist_s* next; } *namelist_t; int main() { namelist_t names = NULL; char new_name[MAX_LENGTH]; do { /* Adding unknown number of records to a list The user can enter as much data as he wants and exhaust the heap */ puts("To quit, enter \"quit\""); puts("Enter record:"); fgets( new_name, MAX_LENGTH, stdin); if (strcmp( new_name, "quit") != 0) { /* Names continue to be added without bothering about the size on the heap */ unsigned int i = strlen(new_name) - 1; if (new_name[i] == '\n') new_name[i] = '\0'; namelist_t new_entry = (namelist_t) malloc( sizeof( struct namelist_s)); if (new_entry == NULL) { /* handle error */ } strcpy( new_entry->name, new_name); new_entry->next = names; names = new_entry; } puts( new_name); } while (strcmp( new_name, "quit") != 0); return 0; }
Compliant Solution
If the objects or data structures are large enough to potentially cause heap exhaustion, the programmer must consider using databases instead, to ensure that records are written to the disk in a timely fashion. Hence, this structure will never outgrow the heap.
In the above example, the user can reuse a single long
variable to store the input and write that value into a simple database containing a table User
with a field userID
along with any other required fields. This will prevent the heap from getting exhausted.
Risk Assessment
It is difficult to identify code that can lead to a heap exhaustion since static analysis tools are currently unable to pinpoint violations. The heap size may also differ in different machines.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MEM12-CPP |
low |
probable |
high |
P2 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website
Other Languages
This rule appears in the C++ Secure Coding Standard as MEM12-CPP. Do not assume infinite heap space.
This rule appears in the Java Secure Coding Standard as FIO03-J. Do not assume infinite heap space.
References
TODO
08. Memory Management (MEM) MEM12-C. Consider using a Goto-Chain when leaving a function on error when using and releasing resources