How do I keep pointers aligned?
Conor P. Cahill
cpcahil at virtech.UUCP
Tue Oct 10 10:08:17 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.
[ sample deleted ]
> 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
The message about pointer alignment has nothing to do with the size of
the pointer itself. It is telling you that it is possible that the
character pointer (which usually can align down to a 1 byte boundry) may
not point to a correctly aligned address required to correctly
dereference the non-char pointer.
For example:
char buffer[20];
long * l;
memset(buffer,'\0',20);
l = (long *) buffer;
printf("l = %d",*l); /* this will *usually* work */
l = (long *) &buffer[1];
printf("l = %d",*l); /* 50-50 chances of a core dump */
The reason for the core dump would be that the CPU requires that all long
words start on a longword boundry (multiple of 4). Trying to de-reference
a longword from an odd address will cause core dumps on half of the systems.
The return from malloc() is guarenteed (by the documentation) to be properly
alligned for all data types, but as far as I know there is no way to tell
lint this. That is why you only get a warning.
--
+-----------------------------------------------------------------------+
| Conor P. Cahill uunet!virtech!cpcahil 703-430-9247 !
| Virtual Technologies Inc., P. O. Box 876, Sterling, VA 22170 |
+-----------------------------------------------------------------------+
More information about the Comp.unix.wizards
mailing list