I'm trying to build a simple linked list where each element would be aligned to some round address. I've tried the following code (shortened as much as possible to be SSCCE):
#include "stdio.h"
#define N 10
typedef struct __attribute__((aligned(0x100)) _element {
int val;
char padding[64];
struct _element *next;
} element;
int main() {
element* head = new element;
element* current = head;
for (int i = 0; i < N; ++i) {
current->val = i;
if (i == N - 1)
break;
current->next = new element;
current = current->next;
}
current->next = NULL;
current = head;
printf("sizeof(element) = 0x%x\n", (unsigned int)sizeof(element));
while (current) {
printf("*(%p) = %d\n", ¤t->val, current->val);
current = current->next;
}
return 0;
}
Built with g++ 4.2.2, no optimizations, and produced:
sizeof(element) = 0x100
*(0x501010) = 0
*(0x501120) = 1
*(0x501230) = 2
*(0x501340) = 3
*(0x501450) = 4
*(0x501560) = 5
*(0x501670) = 6
*(0x501780) = 7
*(0x501890) = 8
*(0x5019a0) = 9
Why aren't the addresses aligned to 0x100? Note that it did affect the struct "size", looks like it's being padded somehow, but it doesn't start at aligned addresses like I wanted.
From this answer I understood that there might be a max alignment, but even lowering it to 0x20 didn't change the alignment (only the sizeof). This answer doesn't help since it's about stack allocation. Couldn't find any other source to explain this. Am I asking too much from this attribute? or doing something else wrong?
Thanks in advance!