...
Type alignment requirements can also affect the size of structures. For example, the size of the following structure is implementation defined:
| Code Block |
|---|
struct s {
int i;
double d;
};
|
Assuming 32-bit integers and 64-bit doubles, for example, the size can range from 12 or 12 to 16 bytes, depending on alignment rules.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* assuming 32-bit pointer, 32-bit integer */
size_t i;
int **matrix = (int **)calloc(100, 4);
if (matrix == NULL) {
/* handle error */
}
for (i = 0; i < 100; i++) {
matrix[i] = (int *)calloc(i, 4);
if (matrix[i] == NULL) {
/* handle error */
}
}
|
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
size_t i;
int **matrix = (int **)calloc(100, sizeof(*matrix));
if (matrix == NULL) {
/* handle error */
}
for (i = 0; i < 100; i++) {
matrix[i] = (int *)calloc(i, sizeof(**matrix));
if (matrix[i] == NULL) {
/* handle error */
}
}
|
Also see recommendation MEM02-C. Immediately cast the result of a memory allocation function call into a pointer to the allocated type for a discussion on the use of the sizeof operator with memory allocation functions.
Exceptions
EXP09-EX1: C99 explicitly The C standard explicitly declares sizeof(char) == 1. So , so any sizes based on characters or character arrays may be evaluated without using sizeof. This does not apply to char* or any other data types.
...
Tool | Version | Checker | Description | section|||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| | Section | Can detect violations of this recommendation. In particular, it looks for the size argument of and flags when it does not find a ; in this case a string is being allocated, and | ||||||||
| Section | |
| 201 S section | Partially Implementedimplemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: EXP09-CPP. Use sizeof to determine the size of a type or variable
ISO/IEC 9899:19992011 Section 6.2.6, "Representations of types," and Section 6.5.3.4, "The sizeof operator and _Alignof operators"
MITRE CWE: CWE-805, "Buffer Access with Incorrect Length Valueaccess with incorrect length value"
Bibliography
...