...
In this example, the user defined function calc_size()
(not shown) is used to calculate the size of the string other_srting. The result of calc_size()
is returned to str_size
and used as the size parameter in a call to malloc()
. However, if calc_size
returned zero, then when the strncpy()
is executed, a heap buffer overflow will occur.
Code Block |
---|
int main(int argc, char *argv[]) { int *i_list = NULL; size_t size; if (argc != 2) { return -1; } size = atoi(argv[1]); if (size == 0) { /* Handle Error */ } i_list = (int*)malloc(size); if (i_list == NULL) { /* Handle Allocation Error */ } /* } } Continue Processing list */ |
Compliant Code Example 1
To assure that zero is never passed as a size argument to malloc()
, a check must be made on the size
parameter.
Code Block |
---|
int main(int argc, char *argv[]) { char *str = NULL; size_t size; if (argc != 2) { /* Handle Arguments Error */ } size = strlen(argv[1])+1; if (size == 0) { /* Handle Error */ } strlist = (int*)malloc(size); if (stri_list == NULL) { /* Handle Allocation Error */ } strcpy(str, argv[1]); /* ProcessContinue Processing strlist */ return 0; } |
References
- Seacord 05 Chapter 4 Dynamic Memory Management