Here's an idea
Posted Dec 10, 2007 7:25 UTC (Mon) by
jzbiciak (
✭ supporter ✭, #5246)
In reply to:
Here's an idea by pr1268
Parent article:
Memory access and alignment
Yes. On an architecture with alignment constraints, the "packed[3]" field isn't necessary. The compiler will insert padding. You can check this out with the offsetof() macro.
For example, if I compile the following program on my 64-bit Opteron, you can see the pointers all get aligned to 8 byte boundaries like they're supposed to. If I compile it on a 32 bit machine, they get aligned to 4 byte boundaries. This is regardless of whether that filler field is there.
#include <stdio.h>
#include <stddef.h>
typedef unsigned int uint32_t;
typedef struct obj_1
{
uint32_t a, b;
char c;
char filler[3];
uint32_t* p1;
char** p2;
char** p3;
} obj_1;
typedef struct obj_2
{
uint32_t a, b;
char c;
uint32_t* p1;
char** p2;
char** p3;
} obj_2;
int main()
{
printf("offset of obj_1.a: %5d bytes\n", offsetof(obj_1, a));
printf("offset of obj_1.b: %5d bytes\n", offsetof(obj_1, b));
printf("offset of obj_1.c: %5d bytes\n", offsetof(obj_1, c));
printf("offset of obj_1.filler: %5d bytes\n", offsetof(obj_1, filler));
printf("offset of obj_1.p1: %5d bytes\n", offsetof(obj_1, p1));
printf("offset of obj_1.p2: %5d bytes\n", offsetof(obj_1, p2));
printf("offset of obj_1.p3: %5d bytes\n", offsetof(obj_1, p3));
putchar('\n');
printf("offset of obj_2.a: %5d bytes\n", offsetof(obj_2, a));
printf("offset of obj_2.b: %5d bytes\n", offsetof(obj_2, b));
printf("offset of obj_2.c: %5d bytes\n", offsetof(obj_2, c));
printf("offset of obj_2.p1: %5d bytes\n", offsetof(obj_2, p1));
printf("offset of obj_2.p2: %5d bytes\n", offsetof(obj_2, p2));
printf("offset of obj_2.p3: %5d bytes\n", offsetof(obj_2, p3));
putchar('\n');
printf("sizeof(int) = %d bytes\n", sizeof(int));
printf("sizeof(long) = %d bytes\n", sizeof(long));
printf("sizeof(void*) = %d bytes\n", sizeof(void*));
return 0;
}
Output on a 32-bit machine:
offset of obj_1.a: 0 bytes
offset of obj_1.b: 4 bytes
offset of obj_1.c: 8 bytes
offset of obj_1.filler: 9 bytes
offset of obj_1.p1: 12 bytes
offset of obj_1.p2: 16 bytes
offset of obj_1.p3: 20 bytes
offset of obj_2.a: 0 bytes
offset of obj_2.b: 4 bytes
offset of obj_2.c: 8 bytes
offset of obj_2.p1: 12 bytes
offset of obj_2.p2: 16 bytes
offset of obj_2.p3: 20 bytes
sizeof(int) = 4 bytes
sizeof(long) = 4 bytes
sizeof(void*) = 4 bytes
Output on a 64-bit machine:
offset of obj_1.a: 0 bytes
offset of obj_1.b: 4 bytes
offset of obj_1.c: 8 bytes
offset of obj_1.filler: 9 bytes
offset of obj_1.p1: 16 bytes
offset of obj_1.p2: 24 bytes
offset of obj_1.p3: 32 bytes
offset of obj_2.a: 0 bytes
offset of obj_2.b: 4 bytes
offset of obj_2.c: 8 bytes
offset of obj_2.p1: 16 bytes
offset of obj_2.p2: 24 bytes
offset of obj_2.p3: 32 bytes
sizeof(int) = 4 bytes
sizeof(long) = 8 bytes
sizeof(void*) = 8 bytes
(
Log in to post comments)