Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say <code>__attribute__((__packed__))</code> or <code>#pragma pack(1)</code>, what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.</p> <p>Perhaps we can blame the compiler for it's complacency though. While gcc does have a <code>-Wcast-align</code> option, it isn't enabled by default nor with <code>-Wall</code> or <code>-Wextra</code>. This is apparently due to gcc developers considering this type of code to be a brain-dead "<a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51628#c5">abomination</a>" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.</p> <p>Consider the following:</p> <pre><code>struct __attribute__((__packed__)) my_struct { char c; int i; }; struct my_struct a = {'a', 123}; struct my_struct *b = &amp;a; int c = a.i; int d = b-&gt;i; int *e __attribute__((aligned(1))) = &amp;a.i; int *f = &amp;a.i; </code></pre> <p>Here, the type of <code>a</code> is a packed struct (as defined above). Similarly, <code>b</code> is a pointer to a packed struct. The type of of the expression <code>a.i</code> is (basically) an int <a href="http://en.wikipedia.org/wiki/Value_%28computer_science%29">l-value</a> with 1 byte alignment. <code>c</code> and <code>d</code> are both normal <code>int</code>s. When reading <code>a.i</code>, the compiler generates code for unaligned access. When you read <code>b-&gt;i</code>, <code>b</code>'s type still knows it's packed, so no problem their either. <code>e</code> is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment <code>f = &amp;a.i</code>, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by <em>default</em> (not even in <code>-Wall</code> or <code>-Wextra</code>).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload