Note that there are some explanatory texts on larger screens.

plurals
  1. POMis-aligned pointers on x86
    text
    copied!<p>Can someone provide an example were casting a pointer from one type to another fails due to mis-alignment?</p> <p>In the comments to <a href="https://stackoverflow.com/questions/544928/reading-integer-size-bytes-from-a-char-array/544964#544964">this answer</a>, bothie states that doing something like</p> <pre><code>char * foo = ...; int bar = *(int *)foo; </code></pre> <p>might lead to errors even on x86 if alignment-checking is enabled.</p> <p>I tried to produce an error condition after setting the alignment-check flag via <code>set $ps |= (1&lt;&lt;18)</code> in GDB, but nothing happened.</p> <p>What does a working (ie non-working ;)) example look like?</p> <hr> <p>None of the code snippets from the answers fail on my system - I'll try it with a different compiler version and on a different pc later.</p> <p>Btw, my own test code looked like this (now also using asm to set <code>AC</code> flag and unaligned read and write):</p> <pre><code>#include &lt;assert.h&gt; int main(void) { #ifndef NOASM __asm__( "pushf\n" "orl $(1&lt;&lt;18),(%esp)\n" "popf\n" ); #endif volatile unsigned char foo[] = { 1, 2, 3, 4, 5, 6 }; volatile unsigned int bar = 0; bar = *(int *)(foo + 1); assert(bar == 0x05040302); bar = *(int *)(foo + 2); assert(bar == 0x06050403); *(int *)(foo + 1) = 0xf1f2f3f4; assert(foo[1] == 0xf4 &amp;&amp; foo[2] == 0xf3 &amp;&amp; foo[3] == 0xf2 &amp;&amp; foo[4] == 0xf1); return 0; } </code></pre> <p>The assertion passes without problems, even though the generated code definitely contains the unaligned access <code>mov -0x17(%ebp), %edx</code> and <code>movl $0xf1f2f3f4,-0x17(%ebp)</code>.</p> <hr> <p>So will setting <code>AC</code> trigger a <code>SIGBUS</code> or not? I couldn't get it to work on my Intel dual core laptop under Windows XP with none of the GCC versions I tested (MinGW-3.4.5, MinGW-4.3.0, Cygwin-3.4.4), whereas codelogic and Jonathan Leffler mentioned failures on x86...</p>
 

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