Skip to content

Instantly share code, notes, and snippets.

@macmade
Created April 2, 2014 21:38
Show Gist options
  • Save macmade/9943724 to your computer and use it in GitHub Desktop.
Save macmade/9943724 to your computer and use it in GitHub Desktop.
An example of C99 strict aliasing issue...
#include <stdio.h>
struct s1
{
int i;
};
struct s2
{
int i;
};
static int __f( struct s1 * s1, struct s2 * s2 );
static int __f( struct s1 * s1, struct s2 * s2 )
{
if( s1->i == 1 )
{
s2->i = 0;
}
return s1->i;
}
int main( void )
{
struct s1 s1;
struct s1 * s1p;
struct s2 * s2p;
s1.i = 1;
s1p = &s1;
s2p = ( struct s2 * )&s1;
printf( "%i\n", __f( s1p, s2p ) );
return 0;
}
@romac
Copy link

romac commented Apr 2, 2014

Weird:

❯❯❯ gcc -std=c99 strict-aliasing-bug.c && ./a.out
0

❯❯❯ gcc -std=c99 -fstrict-aliasing strict-aliasing-bug.c && ./a.out
0

❯❯❯ gcc -std=c99 -fno-strict-aliasing strict-aliasing-bug.c && ./a.out
0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment