Re: ISO: help porting C code to 64 bit linux platform

Jan Panteltje <pNaonStpealmtje@xxxxxxxxx> writes:

On a sunny day (Sat, 13 Jan 2007 11:58:03 +0000) it happened
=?iso-8859-1?Q?M=E5ns_Rullg=E5rd?= <mru@xxxxxxxxxxxxx> wrote in

Jan Panteltje <pNaonStpealmtje@xxxxxxxxx> writes:

On a sunny day (Fri, 12 Jan 2007 19:25:08 +0000) it happened
=?iso-8859-1?Q?M=E5ns_Rullg=E5rd?= <mru@xxxxxxxxxxxxx> wrote in

Emmanuel Fleury <emmanuel.fleury@xxxxxxxx> writes:

Måns Rullgård wrote:

That is a good example of how *not* to write code. *Never*, ever read
or write a struct directly to/from a file. The compiler is free to
insert padding wherever it likes in a struct.

I have to still see that happen in gcc, do you have a code example?

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

struct pad {
uint16_t foo;
uint32_t bar;

int main(int argc, char **argv)
printf("%d %d\n", offsetof(struct pad, foo), offsetof(struct pad, bar));
return 0;

$ gcc foo.c
$ ./a.out
0 4

See the 2 bytes of padding?

OK, I see it, I ran some more tests on code I wrote, maye have to do
some re-writing.
The fun thing is, some has been out there, and been downloaded a
thousand times, and confirmed OK on 32 and 64 bits....
I am now trying to see why (I think I was lucky :-) ).
mm I found why I think, yes, interesting, variables overlap and it
works because 2 zeros then overlap... because of and even number of
16 bit vars in pairs :-)!!

Yes, if all struct members are aligned at their natural alignment
without padding, the compiler doesn't usually change anything. That
doesn't mean that it never will, though, so never depend on it.

I fail to see the relevance of this to the current discussion.

The discussion was about 32 bits to 64 bits.
The more bits the more bloat this example is.
int as return (where a bool is used),
and int as argument (where a 8 bits char is used).

An int takes no more space than a char in a register. When arguments
are passed on the stack, they are still typically aligned on word
boundaries, so there would be no savings there either.

Måns Rullgård