|Fundamental C - Pointers, Cast & Type Punning|
|Written by Harry Fairhead|
|Monday, 10 September 2018|
Page 4 of 4
Type Punning and Undefined Behaviour
Unfortunately as type cast punning isn’t architecture independent and the C89, C99 and C11 standard introduced a strict aliasing policy. This demands that if pointers reference the same memory then their types are compatible. Essentially this means that the types have to be effectively the same and so it rules out casting being used for type punning.
Many of the pointer casts in this section break strict aliasing and hence are undefined behavior. In practice type cast punning is very commonly used in low level programs that target particular machine architectures and nearly all C compilers allow it unless you set an optimization level greater than the default.
If you want GCC to flag such errors you need to include the command line options:
What can you do if you want to avoid the threat of undefined behavior?
One common approach is to find out how to turn strict aliasing off in the compiler you are using. For GCC including the option
turns off strict aliasing restrictions.
The best alternative is to use a union – see later in this chapter. This approach is allowed in C99 and C11 but note it isn’t allowed in C++ which is why you will sometimes be told that you can’t do it.
Another alternative is to use the memcpy function which works like strcpy but with any blocks of memory not just strings. This will copy the bits from one type to another and doesn’t care that they are of different types.
float pi = 3.14; int tempint; memcpy(&tempint,&pi,sizeof(tempint)); printf("%d,\n",tempint);
This copies the bits in the first four bytes of the float into the int and achieves the type punning without violating strict alias rules.
Of course this is less efficient than type cast punning but it is claimed that the compiler will notice it and remove the copy operation.
As Linus Torvalds commented after a strict alias problem was uncovered:
Why do you think the kernel uses "-fno-strict-aliasing"?
The gcc people are more interested in trying to find out what can be allowed by the c99 specs than about making things actually work. The aliasing code in particular is not even worth enabling, it's just not possible to sanely tell gcc when some things can alias.
Fundamental C: Getting Closer To The Machine
Now available as a paperback and ebook from Amazon.
Also see the companion volume: Applying C
or email your comment to: email@example.com
|Last Updated ( Monday, 10 September 2018 )|