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

Copy
   extern char* getData();
   void foo()
   {
     char* ptr = getData();
     unsigned int ptrValue = (unsigned int)ptr;
       printf("Got data from: %d\n", ptrValue);
   }

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

Copy
   extern char* getData();
   void foo()
   {
     char* ptr = getData();
     void* ptrValue = (void*)ptr;
       printf("Got data from: %p\n", ptrValue);
   }

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

Security training

Application security training materials provided by Secure Code Warrior.