Versions Compared

Key

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

Do not convert a pointer value to a pointer type that is more strictly aligned than the referenced type the value actually points toDifferent alignments are possible for different types of objects. If the type-checking system is overridden by an explicit cast or the pointer is converted to a void pointer (void *) and then to a different type, the alignment of an object may be changed.

...

In this compliant solution, the char value is stored into an object of type int so that the pointer's value will be properly aligned:

Code Block
bgColor#ccccff
langc
#include <assert.h>
 
void func(void) {
  char c = 'x';
  int i = c;
  int *ip = (int *)&i;

  assert(ip == &i);
}

Compliant Solution (C11, alignas())

This compliant solution uses the alignment specifier 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:

...

The C Standard allows any object pointer to be cast to and from void *. As a result, it is possible to silently convert from one pointer type to another without the compiler diagnosing the problem by storing or casting a pointer to void * and then storing or casting it to the final type. In this noncompliant code example, loop_function() is passed the char pointer loop_ptr but returns an object of type int pointer:

Code Block
bgColor#FFCCCC
langc
int *loop_function(void *v_pointer) {
  /* ... */
  return v_pointer;
}
 
void func(char *loop_ptr) {
  int *int_ptr = loop_function(loop_ptr);

  /* ... */
}

This example compiles without warning. However, v_pointer can be more strictly aligned than an object of type int *.

Compliant Solution

Because the input parameter directly influences the return value, and loop_function() returns an object of type int *, the formal parameter v_pointer is redeclared to accept only an object of type int *:

Code Block
bgColor#ccccff
langc
int *loop_function(int *v_pointer) {
  /* ... */
  return v_pointer;
}
 
void func(int *loop_ptr) {
  int *int_ptr = loop_function(loop_ptr);

  /* ... */
}

...

Some architectures require that pointers are correctly aligned when accessing objects larger than a byte. However, it is common is in system code that unaligned data (for example, the network stacks) must be copied to a properly aligned memory location, such as in this noncompliant code example:

...

EXP36-EX1: Some hardware architectures have relaxed requirements with regard to pointer alignment. Using a pointer that is not properly aligned is correctly handled by the architecture, although there might be a performance penalty. On such an architecture, improper pointer alignment is permitted , but remains an efficiency problem.

...