Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Aliasing through a union pointer Date: Mon, 23 Nov 2015 15:49:57 -0800 Organization: None to speak of Lines: 53 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="24310"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19fwENR/k8IYN3xJnMFep2J" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:zzby5oDQxbdvkma779AIxPwMBXQ= sha1:ZvyMKmzCSghS0t/9dnVXBw+qysI= Xref: csiph.com comp.lang.c:77046 Jorgen Grahn writes: > On Mon, 2015-11-23, David Brown wrote: > ... >> I'd advise against __attribute__((packed)) (or equivalents on other >> compilers) - either it makes no difference because there is no padding, >> or you will end up with structures with fields that don't match their >> alignment. On some targets, that means run-time errors - on others, it >> means seriously degraded code speed. So it is rarely a good idea. > > I think I agree, but are there really cases where you say > __attribute__((packed)) and then suffer a crash because of it? The > compiler shouldn't generate a struct, and code to access it which will > crash if it's ever run. Yes -- at least on systems where a misaligned access causes a crash. (On x86 and x86_64, it doesn't; it's just a little slower.) For example, given: struct foo { char c; int x; } __attribute__((packed)); if a struct foo object is, say, 4-byte aligned, then the member x is likely to be misaligned. If you refer to the x member of a struct foo object: struct foo obj; obj.x; then gcc knows it's a member of a packed struct, and will generate whatever code is necessary to access it. But if you take the address: int *ptr = &obj.x; ... *ptr ... then gcc will assume that *ptr is properly aligned, and a crash is likely. This could be fixed by disallowing taking the address of misaligned members (as is done for bit fields), or of *any* member of a packed struct, or, less realistically, by generating inefficient code for all dereferences of pointers to types that require nontrivial alignment. See also . -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"