tags:

views:

252

answers:

2

I have the following code:

#include <stdio.h>

int main(void)
{
    int x __attribute__ ((aligned (16))) = 0;
    printf("%lX\n", &x);
    return 0;
}

Compiling and running this code using mingw32-c++.exe (GCC) 3.4.5 (mingw-vista special r3) prints 0x22FF24 which is 0b1000101111111100100100. Compiling and running this code using g++ (Debian 4.3.2-1.1) 4.3.2 prints 0x7FFFF470EE90 which is 0b11111111111111111110100011100001110111010010000.

Due to the alignment I expect the last 7 bits of the variable's address to be zero. Do I make an error in reasoning here? What's going on?

Thanks in advance,

Sebastian

+1  A: 

Check the answer to question GCC __attribute__((aligned(x)) explanation which says:

Because the stack pointer could be anything when the function starts, there is no way to align the array without allocating a lot more than you need and adjusting it

mloskot
+2  A: 

16=24, so I would expect the last 4 bits of the address to be zero if the address was aligned to a 16-byte boundary.

The stack is generally not guaranteed to have any sort of alignment on x86, see Bug 16660. Also, GCC is dependent on the linker for alignment of global/common variables, and binutils prior to 2.20 were not really capable of doing so on Windows.

ephemient
You are right, I misinterpreted the parameters meaning. For alignment to 7 bits I should specify `__attribute__ ((aligned (128)))`. Thanks!
Sebastian