...
Non-compliant Code Example 1
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 a dynamic array of integers is allocated to store s
elements. However, if s
is zero, the call to malloc(s)
will return a reference to a block of memory of size 0. When data is copied to this location, a heap-buffer overflow will occur.
Code Block |
---|
list = (int*)malloc(sizes); if (i_list == NULL) { /* Handle Allocation Error */ } /* Continue Processing list */ |
...
To assure that zero is never passed as a size argument to malloc()
, a check must be made on the size, s
, parameter.
Code Block |
---|
if (size s== 0) { /* Handle Error */ } list = (int*)malloc(sizes); if (i_list == NULL) { /* Handle Allocation Error */ } /* Continue Processing list */ |
References
- Seacord 05 Chapter 4 Dynamic Memory Management