...
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 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 */
}
}
|
Compliant Solution
This compliant solution replaces the hard-coded value 4 with sizeof(int *).
| 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 MEM02-A. 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.
...