You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Never hardcode datatype sizes into an application. Instead, use the sizeof operator to retrieve 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.

Additionally, a datatype can have different representations under different platforms, even when compiled for the same architecture type! Consider the following code.

struct s {
  int i;
  double d;
};

void main() {
  size_t sz = sizeof(struct s);
  printf("Size of struct s: %n bytes.\n", (int) sz);
}

On GNU/Linux on an x86 processor, the output of this program is:
Size of struct s: 12 bytes

On Windows platforms on an x86 processor, the output of this program is:
Size of struct s: 16 bytes

Non-Compliant Coding Example

Compliant Solution

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSCxx-C

3 (high)

3 (probable)

2 (medium)

P18

L1

  • No labels