...
Type alignment requirements can also affect the size of structs. Consider structures. For example, the size of the following structure is implementation-dependent:.
| Code Block |
|---|
struct s {
int i;
double d;
};
|
Depending on the compiler and platform, this structure could be any of a variety of sizes. Assuming 32-bit integers and 64-bit doubles, for example, the size might be can range from 12 or 16 bytes, depending on alignment rules.
Non-Compliant
...
Code Example
This non-compliant code example demonstrates the incorrect way to declare a triangular three-dimensional array of integers. On a platform with 64-bit integers, the loop will access memory outside the allocated memory section.
| Code Block | ||
|---|---|---|
| ||
/* assuming 32-bit pointer, 32-bit integer */
size_t i;
int ** triarray = calloc(100, 4);
if (triarray == NULL) {
/* handle error */
}
for (i = 0; i < 100; i++) {
triarray[i] = calloc(i, 4);
if (triarray[i] == NULL) {
/* handle error */
}
}
|
Compliant Solution
The above example can be fixed by replacing This compliant solution replaces the hard-coded value 4 with the size of the type using sizeof sizeof(int).
| Code Block | ||
|---|---|---|
| ||
size_t i;
int **triarray = calloc(100, sizeof(int *));
if (!triarray) {
/* handle error */
}
for (i = 0; i < 100; i++) {
triarray[i] = calloc(i, sizeof(int));
if (!triarray[i]) {
/* handle error */
}
}
|
...