Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Do not hardcode datatype sizes hard-code the size of a type into an application. Instead, use Because of alignment, padding, and differences in basic types (e.g., 32-bit versus 64-bit pointers), the size of most types can vary between compilers and even version of the same compiler. Using the sizeof operator to retrieve determine sizes improves the size of a datatype.

When writing portable code, it is important to realize that different architectures may represent the same datatype in different manners. For example, a generic pointer (type void*) is 32 bits on x86 and 64 bits on x64.

clarity of what is meant and ensures that changes between compilers or version will not affect the code.

Type Datatype alignment requirements can also affect the size of structs. Consider the following code.structure:

Code Block
typedef struct s {
   int i;
   double d;
} mystruct;

size_t size = sizeof(mystruct);
printf("Size of struct: %d bytes\n", size);

When compiled for Andrew Linux (x86), the output of this program is:
Size of struct: 12 bytes

Depending on the compiler and platform, this structure could be any of a variety of sizes. Assuming 32-bit integers and 64-bit doubles, the size might be 12 or 16 bytes, depending on alignment rules.When compiled for Windows (x86), the output of this program is:
Size of struct: 16 bytes

Non-Compliant Coding Example

This non-compliant example demonstrates the incorrect way to declare a triangular array of integers. On a platform with 64-bit integers, the loop will access memory outside the allocated memory section.

Code Block
bgColor#FFcccc
/* 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 the hard-coded value 4 with the actual size of the datatype as represented on the target platform. Remember to check the return value of the memory allocation routinestype using sizeof.

Code Block
bgColor#ccccff
size_t i;
int **triarray = calloc(100, sizeof(int *));

if (!triarray) {
   /* perform cleanup, returnhandle error */ 
}

for (i = 0; i < 100; i++) {
   triarray[i] = calloc(i, sizeof(int));
   if (!triarray[i]) {
      /* performhandle cleanup, return error */
   }
}

Risk Assessment

If non-compliant code is ported to a different platform, it could introduce a heap buffer or stack overflow vulnerability.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXPxx-A

3 (high)

1 (unlikely)

2 (medium)

P6

L2

References

Wiki Markup
\[[ISO/IEC 9899-1999|cplusplus:AA. C++ References#ISO/IEC 9899-1999]\] Section 6.2.6, "Representations of types," and Section 6.5.3.4, "The sizeof operator"