Wiki Markup |
---|
Dynamic memory management is a common source of programming flaws that can lead to security vulnerabilities. Decisions regarding how dynamic memory is allocated, used, and deallocated are the burden of the programmer. Poor memory management can lead to security issues such as heap-buffer overflows, dangling pointers, and double-free issues \[[Seacord 05|AA. C References#Seacord 05]\]. From the programmer's perspective, memory management involves allocating memory, reading and writing to memory, and deallocating memory. |
Allocating and freeing memory in different modules and levels of abstraction may make it difficult to determine when and if a block of memory has been freed, leading to programming defects such as double-free vulnerabilities, accessing freed memory, or writing to freed or unallocated memory.
Wiki Markup |
---|
To avoid these situations, it is recommended that memory be allocated and freed at the same level of abstraction, and ideally in the same code module. This includes the use of the following memory allocation and deallocation functions described in C99 \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3: |
Code Block |
---|
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
|
Failing to follow this recommendation has led to real-world vulnerabilities. For example, freeing memory in different modules resulted in a vulnerability in MIT Kerberos 5 MITKRB5-SA-2004-002 . The MIT Kerberos 5 code in this case contained error-handling logic, which freed memory allocated by the ASN.1 decoders if pointers to the allocated memory were non-null. However, if a detectable error occured, the ASN.1 decoders freed the memory that they had allocated. When some library functions received errors from the ASN.1 decoders, they also attempted to free, resulting in a double-free vulnerability.
...