c++ – What does the data alignment warning mean?

Question:

When compiling code like this for ARM

char* c = 0;
int* p = reinterpret_cast<int*>(c);

GCC prints a warning

cast from 'char *' to 'int *' increases required alignment of target type

What are the consequences of using a reinterpret_cast like this for types with different alignment requirements? Why doesn't this warning appear on all platforms? What is this all about, do you need to fix it somehow?

https://godbolt.org/g/VGDK3w

At the link above, you will see an attempt to compile such code for x86_64 and ARM processors. Despite the same compiler flags, the result is different.

Answer:

The behavior of reinterpret_cast in this case is platform dependent. Since C ++ 11, the behavior of such a conversion is defined as

int* p = static_cast<int *>(static_cast<void *>(c));

and the result will depend on the behavior of the external static_cast . The behavior of static_cast from void * to an object pointer type is unspecified if the source void * address does not meet the alignment requirements of the target type.

  • On one platform, a cast from a pointer with more relaxed alignment requirements to a pointer with more stringent alignment requirements may result in the loss of the original address value, i.e. the compiler and / or hardware will forcefully align the pointer.

  • On another platform, the address value of the pointer will be preserved, but if an attempt is made to access through an unaligned pointer, the program will crash.

  • On the third platform, the address value of the pointer will be preserved, but when accessed through an unaligned pointer, such access will be successful, but less efficient.

  • On the fourth platform, there will be no negative consequences at all.

The data alignment warning can either indicate that similar problems may exist on your platform, or simply be a pedantic "portability warning", i.e. say, your code may behave differently on other platforms.

Scroll to Top