Integer values used in the following manner must be guranteed correct:
- As an array index
- In any pointer arithmetic
- As a length or size of an object
- As the bound of an array (for example, a loop counter)
- In security critical code
The runtime behavior of integers in C is not always well-understood by programmers, leading to exploitable vulnerabilities. For example, assume the following code is compiled and executed on IA-32:
| Code Block |
|---|
signed char sc = SCHAR_MAX;
unsigned char uc = UCHAR_MAX;
signed long long sll = sc + uc;
|
Both the signed char sc and the unsigned char uc are subject to integer promotions in this example. Because all values of the original types can be represented as int, both values are automatically converted to int as part of the integer promotions. Further conversions are possible, if the types of these variables are not equivalent as a result of the "usual arithmetic conversions". The actual addition operation in this case takes place between the two 32-bit int values. This operation is not influenced by the resulting value is stored in a signed long long integer. The 32-bit value resulting from the addition is simply sign-extended to 64-bits after the addition operation has concluded.
...
Recommendations
Use size_t for all integer values representing the size of an object
...