...
| Wiki Markup |
|---|
This example, taken from \[[MEM32-C. Detect and handle critical memory allocation errors]\] demonstrates why checking the return value of memory allocation routines is critical. The buffer {{input_string}} is copied into dynamically allocated memory referenced by {{str}}. However, the result of {{malloc()}} is not checked before {{str}} is referenced. Consequently, if {{malloc()}} fails, the program will abnormally terminate. |
| Code Block | ||
|---|---|---|
| ||
/* ... */
size_t size = strlen(input_string);
if (size == SIZE_MAX) {
/* Handle Error */
}
str = malloc(size+1);
strcpy(str, input_string);
/* ... */
free(str);
|
Compliant Solution (Memory Management)
Upon failure, the malloc() function returns NULL. Failing to handle this error condition appropriately can lead to abnormal and abrupt program termination.
...