PORTING.CAST.PTR.SIZE

Pointer cast 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.PTR.SIZE checker detects a pointer cast to a type of a potentially incompatible 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(long* pl)
   {
     int i, *pi;
       i = 32;
       pi = &i;
       *pl = *(long*)pi;   // PORTING.CAST.PTR.SIZE
   }

The C standard provides no explicit size requirements (except relative requirements) for integral types, so compiler providers are at liberty to design 'int' and 'long' (and 'long long') in any way, as long as they don't break the relative size requirements (long must be at least as large as int, and so on). The code shown in this example works on a typical 32-bit implementation, but fails on most 64-bit implementations.

Fixed code example

Copy
   void foo(long* pl)
   {
     int i, *pi;
       i = 32;
       pi = &i;
       *pl = 0L | *(int*)pi;
   }

The fixed code ensures that the code can be ported to a 64-bit platform without a problem.

Related checkers

PORTING.CAST.SIZE

Security training

Application security training materials provided by Secure Code Warrior.