...
Noncompliant Code Example
In this noncompliant example, the user-defined function get_size() (not shown) is used to calculate the size requirements for a dynamic array of long int that is assigned to the variable num_elements. When calloc() is called to allocate the buffer, num_elements is multiplied by sizeof(long) to compute the overall size requirements. If the number of elements multiplied by the size cannot be represented as a size_t, then calloc() may allocate a buffer of insufficient size. When data is copied to that buffer, a buffer an overflow may occur.
| Code Block | ||
|---|---|---|
| ||
size_t num_elements;
/* initialize num_elements to the number of elements needed */
long *buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
/* Handle error condition */
}
/*...*/
free(buffer);
buffer = NULL;
|
...
| Code Block | ||
|---|---|---|
| ||
long *buffer;
size_t num_elements;
/* initialize num_elements to the number of elements needed */
if (num_elements > SIZE_MAX/sizeof(long)) {
/* Handle error condition */
}
buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
/* Handle error condition */
}
|
...