...
Wiki Markup |
---|
To avoid these situations, itmemory is recommended that memory should 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 Section 7.20.3 \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\]: |
...
Wiki Markup |
---|
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 \[[MIT 04|AA. C References#MIT 04]\]. 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-NULLnull. However, if a detectable error occurred, 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 the same memory, resulting in a double-free vulnerability. |
...
Code Block | ||
---|---|---|
| ||
enum { MIN_SIZE_ALLOWED = 32 };
int verify_size(char *list, size_t size) {
if (size < MIN_SIZE_ALLOWED) {
/* Handle Error Condition */
free(list);
return -1;
}
return 0;
}
void process_list(size_t number) {
char *list = (char *)malloc(number);
if (list == NULL) {
/* Handle Allocation Error */
}
if (verify_size(list, number) == -1) {
free(list);
return;
}
/* Continue Processing list */
free(list);
}
|
...