Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
struct ptrflag {
  char *pointer;
  unsigned int flag :9;
} ptrflag;
/* ... */
ptrflag.pointer = ptr;
ptrflag.flag = flag;

Non-Compliant Code Example

This non-compliant code example attempts to determine whether two character pointers are aligned to each other.

Code Block
bgColor#FFcccc

char *ptr1;
char *ptr2;
/* ... */
if (((unsigned)ptr1 & 3) == ((unsigned)ptr2 & 3)) {
  /* ... */

Although this comparison is likely to work on many architectures, it is much less portable than it could be.

Compliant Solution

On machines where pointers can be represented as integers, the types intptr_t and uintptr_t are provided for that purpose.  They are only guaranteed to be able to receive void pointers.

Code Block
bgColor#ccccff

#include <stdint.h>
enum { ALIGN_MASK = 3 };
/* ... */
char *ptr1;
char *ptr2;
/* ... */
if (((uintptr_t)(void *)ptr1 & ALIGN_MASK) == ((uintptr_t)(void *)ptr2 & ALIGN_MASK)) {
  /* ... */

The header inttypes.h can be used instead of stdint.h to get the integer types in a hosted environment.

Risk Analysis

Converting from pointer to integer or vice versa results in unportable code and may create unexpected pointers to invalid memory locations.

...