Related articles |
---|
Permuting fields of records garavel@imag.fr (1993-06-04) |
Re: Permuting fields of records drw@runge.mit.edu (1993-06-06) |
C structure padding drw@zermelo.mit.edu (1993-06-26) |
Re: C structure padding pat@tesuji.qc.ca (1993-06-27) |
Re: C structure padding lord+@andrew.cmu.edu (Tom Lord) (1993-06-27) |
Re: C structure padding jqb@netcom.com (1993-06-27) |
Re: C structure padding drw@phragmen.mit.edu (1993-06-28) |
Re: C structure padding jqb@netcom.com (1993-06-28) |
Re: C structure padding msb@sq.sq.com (1993-06-29) |
Newsgroups: | comp.compilers |
From: | drw@zermelo.mit.edu (Dale R. Worley) |
Keywords: | optimize, C, comment |
Organization: | MIT Dept. of Tetrapilotomy, Cambridge, MA, USA |
References: | 93-06-012 93-06-017 |
Date: | Sat, 26 Jun 1993 19:36:10 GMT |
I wrote:
However, ANSI C requires that the fields of a struct be allocated in the
order they are declared. In addition, it may be that structs need not be
padded to a multiple of their alignment restriction. (Can "struct { short
a; char b; }" be allocated only 3 bytes?)
James Jones <jejones@microware.com> writes:
Depends. If the target processor is serious about alignment, i.e. it
gets an exception on unaligned memory references to shorts, then arrays
and pointer arithmetic wouldn't work if the size of the structure were
three.
This leads up to a point that I've never seen satisfactorily resolved:
Must a structure be padded when it is *not* part of an array? I've never
seen anything in the Standard that makes it clear that such a structure
must be padded, bit it seems clear that padding is necessary for common
programming paradigms to work. Am I missing something?
For example: Suppose we have a machine with the length and alignment
requirements:
integer length 4 alignment 4
char length 1 alignment 1
If I have a structure:
struct tag { int a; char b; };
Then the fields pretty much have to be laid out with a at offset 0 and
b at offset 4 (although that isn't critical). But the whole structure
has an alignment requirement of 4, and so *in an array*, each
structure has to be padded out to 8 bytes. In particular,
sizeof(struct tab) must be 8.
But-- If I just declare a variable with type struct tag, must the full
8 bytes be allocated to it, or can the compiler give it 5 and pack
some other variable(s) in the following 3 bytes?
I recall nothing in the Standard which prevents the compiler from
doing such tricks. But the code
struct tag v;
char p;
struct tag w;
char q;
memcpy(w, v, sizeof(w));
would mess up p and q if the compiler packed them into the padding of
v and w.
Dale
Dale Worley Dept. of Math., MIT drw@math.mit.edu
[It's pretty clear that all structures have to be treated the same, since
if p and q are pointers to structures, you can write *p = *q regardless of
whether they're pointing to simple structures or into an array. -John]
--
Return to the
comp.compilers page.
Search the
comp.compilers archives again.