...
Code Block | ||||
---|---|---|---|---|
| ||||
size_t num_elements;
long *buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
/* Handle error condition */
}
/*...*/
free(buffer);
buffer = NULL;
|
...
In this compliant solution, the the two arguments num_elements
and sizeof(long)
are checked before the call to calloc()
to determine if wrapping will occur.
Code Block | ||||
---|---|---|---|---|
| ||||
long *buffer;
size_t num_elements;
if (num_elements > SIZE_MAX/sizeof(long)) {
/* Handle error condition */
}
buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
/* Handle error condition */
}
|
Note that the maximum amount of allocatable memory is typically limited to a value less than SIZE_MAX
(the maximum value of size_t
). Always check the return value from a call to any memory allocation function in compliance with rule MEM32-C. Detect and handle memory allocation errors.
...
Tool | Version | Checker | Description | |
---|---|---|---|---|
Section | Compass/ROSE |
|
|
|
Related Vulnerabilities
...
CERT C++ Secure Coding Standard: MEM07-CPP. Ensure that the arguments to calloc(), when multiplied, can be represented as a size_t
ISO/IEC 9899:19992011 Section 7.1820.3, "Limits of other integer types"
MITRE CWE: CWE-190, "Integer Overflow overflow (Wrap wrap or Wraparoundwraparound)"
MITRE CWE: CWE-128, "Wrap-around Errorerror"
Bibliography
[Seacord 2005] Chapter 4, "Dynamic Memory Management"
[RUS-CERT] Advisory 2002-08:02, "Flaw in calloc and similar routines"
[Secunia] Advisory SA10635, "HP-UX calloc Buffer Size Miscalculation Vulnerabilitybuffer size miscalculation vulnerability"
...