Cast of an expression to a type of potentially incompatible size
The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.CAST.SIZE checker detects situations in which an expression is cast to a type of potentially different size.
Vulnerability and risk
Code written for a particular architecture's data model can face significant challenges in porting when the new architecture imposes a new data model. For example, when the code is ported between 32-bit and 64-bit data models, the new data model typically leaves 'int' at 32 bits, but uses 'long' as a 64-bit value, breaking any assumed equality in data type size that worked under the 32-bit data model.
Mitigation and prevention
Best practice involves defining a data model for your code base that is abstracted from any particular compiler's data model or underlying architectural implementation. Many prevalent coding standards enforce this type of abstraction for all types.
Vulnerable code example
int i = 32;
l = (long)i; // PORTING.CAST.SIZE
i = (int)l; // PORTING.CAST.SIZE
This code shows two examples that result in PORTING.CAST.SIZE errors.
- CERT EXP56-CPP: Do not call a function with a mismatched language linkage
- CERT INT18-C: Evaluate integer expressions in a larger size before comparing or assigning to that size
- CERT INT31-C: Ensure that integer conversions do not result in lost or misinterpreted data
- CWE-704: Incorrect Type Conversion or Cast