Weird strict-aliasing break

Steffen Dettmer steffen.dettmer@googlemail.com
Mon May 30 12:40:00 GMT 2011


On Mon, May 30, 2011 Thibault Castel <thibault.castel@gmail.com> wrote:
> I have a weird warning when compiling my program with g++:
>   "dereferencing pointer ‘NAME’ does break strict-aliasing rules"
>
> So, I tried to investigate a little bit and find some clues : I do a
> memory mapping from a char buffer to a C struct to have access to
> different datas into the buffer. Pretty casual. But, when I try to
> access one of my inner field, the warning triggers... Huh...

Beside that this may have other disadvantages, such as depending
on byte order, padding and alighnment issues, in general you
cannot assume that constructions like:

struct s {
   int a; // or int32_t
};
char buffer[];

struct s *p = buffer;   p->a;
struct s *p = buffer+1; p->a;

this even may crash (we had such problems on some ARM CPUs).

I think better here is using memcpy, but still "you have to know
what you are doing".

I think the only 100% correct way is proper deserialisation, maybe this way:

struct s *p = new struct s;
p->a =
      (int)(buffer[0]) * 0x1000000 +
      (int)(buffer[1]) * 0x0010000 +
      (int)(buffer[2]) * 0x0000100 +
      (int)(buffer[3]);

A better workaround for the alignment probably could be something like:

struct s {
   int a; // or int32_t
};
char buffer[];

union x {
    struct s;
    char buffer[1];
}

> I successfully avoid the warning with "__attribute__((__may_alias__))"
> but this "cheat" bother me because :
- you might have a case where it breaks things
  (such as optimization changes behavior)

I hope some expert corrects me where I'm wrong.

oki,

Steffen



More information about the Gcc-help mailing list