https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96293

            Bug ID: 96293
           Summary: Extraneously noisy "taking address of packed member
                    may result in an unaligned pointer value"
           Product: gcc
           Version: 9.3.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lavr at ncbi dot nlm.nih.gov
  Target Milestone: ---

Hi,

Beginning version 9 GCC started to generate tons of warnings of "unaligned
pointer value".  While this may be useful in some cases, many of these warnings
should not be emitted (because the packed attribute is generally used by those,
who follow the layout and usually know, what they are doing), IMO.

Consider the following:

```
#include <stdio.h>

struct S {
    char          a;
    unsigned char b;
    short         c;
    unsigned int  d;
} __attribute__((packed));

void f1(char* p)
{
   *p = '0';
}

void f2(unsigned char* p)
{
   *p = '1';
}

void f3(short* p)
{
    *p = 2;
}

void f4(unsigned int* p)
{
    *p = 3;
}

int main()
{
    struct S s;

    f1(&s.a);
    f2(&s.b);
    f3(&s.c);
    f4(&s.d);
    printf("%c %c %hd %u\n", s.a, s.b, s.c, s.d);
    return 0;
}
```

On most platforms all members of the packed 'struct S' above are well-aligned
to their respective type boundary, and the warnings like:
```
test.c: In function ‘main’:
test.c:36:8: warning: taking address of packed member of ‘struct S’ may result
in an unaligned pointer value [-Waddress-of-packed-member]
   36 |     f3(&s.c);
      |        ^~~~
test.c:37:8: warning: taking address of packed member of ‘struct S’ may result
in an unaligned pointer value [-Waddress-of-packed-member]
   37 |     f4(&s.d);
      |        ^~~~

```
are distracting and unhelpful!

I'd say that GCC should only issue a warning about the alignment if the packed
member does not indeed align with its natural boundary (what would have been
assigned by GCC if the structure wasn't packed).  That is, if the "b" member
above would have been missing, then the warnings are indeed legitimate. 
Otherwise, "c", being a two-byte short integer, is perfectly fine to be located
at offset 2, and "d" (a 4 byte integer) is perfectly fine to be located at
offset 4, there's no need for any warnings.

The same rule should apply for aggregates, too.

Thanks for considering this suggestion.

Reply via email to