...
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[]) { charint *stri_list = NULL; size_t size; if (argc != 2) { return /* Handle Arguments Error */ } -1; } strsize = mallocatoi(strlen(argv[1])+1); if (strsize == NULL0) { /* Handle Allocation Error */ } strcpy(str, argv[1]); /* Process stri_list = (int*)malloc(size); if (i_list == NULL) { /* Handle Allocation Error */ return 0;} } |
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 */ } str = malloc(size); if (str == NULL) { /* Handle Allocation Error */ } strcpy(str, argv[1]); /* Process str */ return 0; } |
...