Fundamental C - Pointers, Cast & Type Punning
Written by Harry Fairhead   
Monday, 10 September 2018
Article Index
Fundamental C - Pointers, Cast & Type Punning
Widening & Narrowing Casts
Type Punning
Undefined Behaviour

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:

-fstrict-aliasing -Wstrict-aliasing

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

-fno-strict-aliasing 

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.

For example:

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.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables 
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation 
  6. Operators and Expression
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays 
      Extract  Ennumerations 
  9. Strings
      Extract  Simple Strings 
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs 
      Extract Typedef ***NEW
  12. Bit Manipulation
      Extract Shifts And Rotates 
  13. Files
     Extract Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C

<ASIN:1871962609>

<ASIN:1871962463>

<ASIN:1871962617>

<ASIN:1871962455>

 

Related Articles

Remote C/C++ Development With NetBeans

Raspberry Pi And The IoT In C

Getting Started With C/C++ On The Micro:bit

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, Facebook or Linkedin.

Banner


Synthesizing The Bigger Picture
09/08/2020

There are more cameras in the world and more people taking photos all the time than ever before. What is more we all tend to take the same shots whenever we are near something "touristy". A new techni [ ... ]



Ants Show The Way To Manage Vehicles
27/07/2020

Before you start fantasizing about ants sitting round a table planning how to route vehicles I'd better tell you that its ant algorithms that are being charged with the task, not the real thing. Of co [ ... ]


More News

graphics

 



 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Monday, 10 September 2018 )