How do I keep pointers aligned?

Chris Calabrese cjc at ulysses.homer.nj.att.com
Tue Oct 10 07:13:07 AEST 1989


In article <12879 at s.ms.uky.edu>, sean at ms.uky.edu (Sean Casey) writes:
> Lint tells me I have possible pointer alignment problems.
> 
> In one case, I'm allocating storage for a struct:
> 
> typedef struct Stuff {
> 	int stufflet;
> 	etc;
> } STUFF;
> 
> s = (STUFF *) malloc((unsigned) sizeof(STUFF));
> 
> Now we all know malloc returns a (char *). What I'm wondering is why
> lint would complain. Aren't all pointers the same size? Does lint think
> that perhaps a four byte pointer might be copied to a two byte pointer
> that is not aligned so that it can be interpreted as a 4BP?
> 
> [ further examples and comments deleted ]

No, all pointers are not created equal!

I worked for a while on a machine (no longer in production) which had
a custom mmu on a 68010 (this was back before the official Motorola
mmu's came out) which did all sorts of weird things with word aligned
pointers of different sizes and really made my head spin sometimes
(this was back when I was a freshman undergraduate before I
learned about lint -p).  Come to think of it, you can do the same
thing on Intel i[023]86 architectures.

Even on normal architecures, however, (char *) must be able to point
to every memory address, whereas (STUFF *) may only be able to point
to word aligned addresses (for efficiency's sake).  Malloc makes sure
that it only passes word alighed pointers, but lint doesn't know
that.  K&R [ANSI] C guarentees that (STUFF *)(char *)type_stuff
[(STUFF *)(void *)type_stuff] works, but not the other way
around.

Hopefully, every malloc implementation gets it right!
-- 
Name:			Christopher J. Calabrese
Brain loaned to:	AT&T Bell Laboratories, Murray Hill, NJ
att!ulysses!cjc		cjc at ulysses.att.com
Obligatory Quote:	``Anyone who would tell you that would also try and sell you the Brooklyn Bridge.''



More information about the Comp.unix.wizards mailing list