Re: struct compatibility
- From: Barry Schwarz <schwarzb@xxxxxxxxx>
- Date: Sat, 04 Feb 2006 22:46:25 -0800
On Tue, 31 Jan 2006 10:29:43 +0100, Christian Kandeler
<christian.kandeler@xxxxxx> wrote:
Hi,
I'd like to know whether the following code is standard-compliant:
struct generic {
int x;
int a[1];
};
void f(struct generic *s)
{
int i;
for (i = 0; i < 10; i++)
s->a[i] = i;
}
int main(void)
{
struct special {
int x;
int a[10];
} s;
f((struct generic *) &s);
The standard guarantees that all pointers to struct have the same
representation. Therefore, casting the value of &s will produce a
representable result. It probably won't even change the
representation.
However, there is no guarantee that a struct special and a struct
generic have the same alignment. If a struct generic has a more
restrictive alignment that the struct special s does not meet, any
attempt to dereference the address, as is done in function f, results
in undefined behavior.
Furthermore, the compiler is allowed to insert different quantities of
padding between i and a in the two different structure types. It is
therefore possible that function f is storing its values in padding of
struct special s (if a struct special has the extra padding) or beyond
the end of struct special s (if a struct generic has the extra
padding). I'm not sure about the first but the second definitely
invokes undefined behavior.
Since it is possible for a compliant compiler to produce this
undefined behavior, the answer has to be the code is not compliant.
.
return 0;
}
- Prev by Date: Re: How can I cause the datetime to be the name of the output file.....
- Next by Date: Re: an enum and ntoh question
- Previous by thread: Re: struct compatibility
- Next by thread: What is the Use Of Static Fuction.
- Index(es):
Relevant Pages
|