MEM-malloc-sizeof
In this section:
Synopsis
Allocating memory with malloc without using sizeof.
Enabled by default
Yes
Severity/Certainty
Low/Medium

Full description
Memory was allocated with malloc() but the sizeof operator might not have been used. Using sizeof when allocating memory avoids any machine variations in the sizes of data types, and consequently avoids under-allocating. To pass this check, assign the address of the allocated memory to a char pointer, because sizeof(char) always returns 1.
Coding standards
- CERT MEM35-C
Allocate sufficient memory for an object
- CWE 131
Incorrect Calculation of Buffer Size
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
void example(void) {
int *x = malloc(4); //no sizeof in malloc call
free(x);
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
void example(void) {
int *x = malloc(sizeof(int));
free(x);
}