Newsgroups: comp.lang.c Path: utzoo!utgpu!jarvis.csri.toronto.edu!dgp.toronto.edu!flaps From: flaps@dgp.toronto.edu (Alan J Rosenthal) Subject: Re: Suitably aligned pointers Message-ID: <8810151524.AA16480@explorer.dgp.toronto.edu> Organization: University of Toronto References: <345@marob.MASA.COM> Date: Sat, 15 Oct 88 11:24:47 EDT In article <345@marob.MASA.COM> daveh@marob.UUCP (Dave Hammond) writes: >The problem is the routines don't return a `suitably aligned' pointer, >so the accuracy of casting the return to other than char * is in doubt. > >Can someone explain the technique used to suitably align a pointer ? Well, it can't be done very nicely in a portable way. It can be done very easily in a machine-dependent way: just do this: if ((long)p & 1) p++; for example to enforce even alignment. Of course, your memory routine will then have to allocate n + 1 bytes, counting the one you just skipped. (Don't assume your machines require even alignment, check it out.) To make it a little more portable, you have to over-align, so to speak -- there is no way to figure out the alignment requirement but there is a way to figure out something which must be a multiple of the alignment requirement. Take all types you can think of (whether or not, for example, you must include all of pointer-to-char, pointer-to-pointer-to-char, and pointer-to-int, can not be determined, and since there are an infinite number of types this problem is not solvable in general). Make a union of them, and then take sizeof it. If you're worried that someone might have taken the ansi draft literally and left out necessary padding of unions, wrap it in a struct first and take sizeof the struct. It is not possible to eliminate the assumption that a pointer can fit into some integral type, although I suppose you could use unsigned long if you think that would help. On machines on which a pointer cannot fit into any integral type, I suppose that a little assembly language is required. ajr -- #define __STDC__ 0