Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: EX2 for valid casts, moved align_as example there

...

EXP36-EX2: If a pointer is known to be correctly aligned to the target type, then a cast to that type is permitted. There are several cases where a pointer is known to be correctly aligned to the target type. The pointer could point to an object declared with a suitable alignas() qualifier. It could point to an object returned by aligned_alloc(), calloc(), malloc(), or realloc(), as per the C standard, section 7.22.3, paragraph 1  [ISO/IEC 9899:2011].

This compliant solution uses the alignment specifier, which is new to C11, to declare the char object c with the same alignment as that of an object of type int. As a result, the two pointers reference equally aligned pointer types:

Code Block
bgColor#ccccff
langc
#include <stdalign.h>
#include <assert.h>
 
void func(void) {
  /* Align c to the alignment of an int */
  alignas(int) char c = 'x';
  int *ip = (int *)&c; 
  char *cp = (char *)ip;
  /* Both cp and &c point to equally aligned objects */
  assert(cp == &c);
}

 

...

Risk Assessment

Accessing a pointer or an object that is not properly aligned can cause a program to crash or give erroneous information, or it can cause slow pointer accesses (if the architecture allows misaligned accesses).

...