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: Expressions
      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
     
    Extract: String I/O ***NEW!!
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs
      Extract Typedef
  12. Bit Manipulation
      Extract Basic Bits
      Extract Shifts And Rotates 
  13. Files
     Extract Files
     
    Extract Random Access 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


Falco On Track To Version 1.0.0
02/04/2024

Falco is a cloud native runtime security tool for the Linux operating system, designed to detect abnormal behavior and warn of potential security threats in real-time. Now it's about to release its fi [ ... ]



GitHub Introduces Code Scanning
26/03/2024

GitHub has announced a public beta of a code scanner that automatically fixes problems. The new feature was announced back in November, but has now moved to public beta status.  


More News

raspberry pi books

 

Comments




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



Last Updated ( Monday, 10 September 2018 )