Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

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


1   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 example


1   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 checkers

PORTING.CAST.SIZE