PORTING.CAST.PTR.SIZEPointer cast to a type of potentially incompatible sizeThe 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 riskCode 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 preventionBest 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 example1 void foo(long* pl) 2 { 3 int i, *pi; 4 i = 32; 5 pi = &i; 6 *pl = *(long*)pi; // PORTING.CAST.PTR.SIZE 7 } 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 example1 void foo(long* pl) 2 { 3 int i, *pi; 4 i = 32; 5 pi = &i; 6 *pl = 0L | *(int*)pi; 7 } The fixed code ensures that the code can be ported to a 64-bit platform without a problem. Related checkersExternal guidelines |