CERT-MEM35-C_b
In this section:
Synopsis
Allocate sufficient memory for an object.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
The types of integer expressions used as size arguments to malloc(), calloc(), realloc(), or aligned_alloc() must have sufficient range to represent the size of the objects to be stored. If size arguments are incorrect or can be manipulated by an attacker, then a buffer overflow may occur.
Coding standards
- CERT MEM35-C
Allocate sufficient memory for an object
- CWE 680
Integer Overflow to Buffer Overflow
- CWE 467
Use of sizeof() on a Pointer Type
- CWE 789
Uncontrolled Memory Allocation
- CWE 131
Incorrect Calculation of Buffer Size
Code examples
The following code example fails the check and will give a warning:
#include <stdint.h>
#include <stdlib.h>
void function(size_t len) {
long *p;
if (len == 0 || len > SIZE_MAX / sizeof(long)) {
return;
}
p = (long *)malloc(len * sizeof(char));
if (p == NULL) {
return;
}
free(p);
}
The following code example passes the check and will not give a warning about this issue:
#include <stdint.h>
#include <stdlib.h>
void function(size_t len) {
long *p;
if (len == 0 || len > SIZE_MAX / sizeof(long)) {
return;
}
p = (long *)malloc(len * sizeof(long));
if (p == NULL) {
return;
}
free(p);
}