Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!linus!philabs!pwa-b!mmintl!franka From: franka@mmintl.UUCP (Frank Adams) Newsgroups: comp.lang.c Subject: Re: pointer cast question Message-ID: <2398@mmintl.UUCP> Date: Mon, 21-Sep-87 18:59:34 EDT Article-I.D.: mmintl.2398 Posted: Mon Sep 21 18:59:34 1987 Date-Received: Fri, 25-Sep-87 06:10:40 EDT References: <100@teletron.UUCP> Reply-To: franka@mmintl.UUCP (Frank Adams) Organization: Multimate International, E. Hartford, CT. Lines: 30 Keywords: pointer cast alignment In article <100@teletron.UUCP> andrew@teletron.UUCP (Andrew Scott) writes: >I am curious as to why ... casting from a pointer to one type to a pointer >to another type may cause address exceptions if the alignment requirements >of the two types differ (as described in section 14.4 of K&R). ... It >seems to me that the cast should produce code which aligns the pointer to a >proper alignment boundary if necessary. ... What is the purpose of such a >cast (other than to make lint happy) if not to convert a valid data value of >one type to a valid data type of another? The reason is speed. Generally speaking, good programming practice (when it produces such casts at all, which is not all that often) will always produce a valid pointer in such cases. The vast majority of such casts in good code fall into one of two categories: 1) Casting the result of a malloc (or other allocation primitive) to the type of the data being allocated. In this case, proper alignment is guaranteed by malloc, so fix up code is a waste of time. 2) A pointer is cast to a less restricted type (for example, "int *" to "char *"), and then back again. On the cast back, there can be no alignment problem, since the value already was in the appropriate form. Furthermore, what is the point of aligning the cast pointer to the proper boundary? This is almost always wrong, and it hides the error from the programmer. (Lots of machines will hide this error anyhow, but there is no point in penalizing the programmers on better architectures.) -- Frank Adams ihnp4!philabs!pwa-b!mmintl!franka Ashton-Tate 52 Oakland Ave North E. Hartford, CT 06108