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

Cast between pointer and non-pointer types

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.CAST.PTR checker searches for a cast between types that aren't both pointers or non-pointers.

Vulnerability and risk

Depending on the platform and architecture in use, pointers may or may not be represented by the same number of bits as an integral type such as unsigned integer, so it's considered unsafe to cast pointers to non-pointer types, and the reverse.

Mitigation and prevention

Don't attempt to store pointer values in integral types. If the pointed-to type really must be hidden, use a void pointer instead.

Vulnerable code example

1   extern char* getData();
2   void foo()
3   {
4     char* ptr = getData();
5     unsigned int ptrValue = (unsigned int)ptr;

6       printf("Got data from: %d\n", ptrValue);
7   }

This interchange of a pointer type with an integral type can be guaranteed to fail on certain platforms, so it should be considered unsafe on all platforms.

Fixed code example

1   extern char* getData();
2   void foo()
3   {
4     char* ptr = getData();
5     void* ptrValue = (void*)ptr;

6       printf("Got data from: %p\n", ptrValue);
7   }

In the fixed example, a void pointer is used instead of the unsafe expression.