PORTING.CAST.SIZE

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

Copy
   void foo()
   {
     int i = 32;
     long l;
       l = (long)i;    // PORTING.CAST.SIZE
       i = (int)l;     // PORTING.CAST.SIZE
   }

This code shows two examples that result in PORTING.CAST.SIZE errors.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.