RISC Machine Data Structure Word Alignment Problems?

Martin Weitzel martin at mwtech.UUCP
Sat Feb 24 09:47:19 AEST 1990


In article <12118 at goofy.megatest.UUCP> djones at megatest.UUCP (Dave Jones) writes:
}From article <645 at mwtech.UUCP), by me (Martin Weitzel):
}) There were some recent postings, that pointed out/complained about
}) 'holes' in C-struct definitions.
}...
}) 
}) My advice in this situation is, to change this code as follows:
}) 
}) char buffer[
}) 	  2 /* length of message */
}) 	+ 1 /* several flag bits
}) 	+ 1 /* type of message */
}) 	+ 4 /* checksum */
}) 	+ 100 /* arbitrary message */
}) ];
}) 
}) #define m_length(b)	(*((short *)        (char *)(b) + 0))
}) #define m_flags(b)	(*((unsigned char *)(char *)(b) + 2))
}) #define m_type(b)	(*((char *)         (char *)(b) + 3))
}) #define m_checksum(b)	(*((unsigned long *)(char *)(b) + 4))
}) #define m_bytes(b)	(                   (char *)(b) + 8 )
}) 
}
}There's probably going to be a flurry of replies telling you why
}this will not work in the general case.
}
}These casts from char* to this-or-that* are not going to work
}unless the data just happen to be properly aligned for whatever
}processor you happen to be using.

I'm well aware that allignment restrictions may invalidate
certain casts from one pointer type to another, but you must
see my proposual in the context of the original questions:

The posters generally complained, that they were not able to
overlay certain byte patterns in memory, because the C-struct
they defined for that purpose contained holes (introduced by
the compiler). The question, by which hard- or software the byte
patterns were produced, was never mentioned in these postings,
but because the posters seemed to be sure, that (only) the
holes in the structures caused the problems, the parts must
have been allready properly aligned 

If the parts of the byte patterns were not properly
aligned, also struct-s *without* holes could not have been
used for this purpose(%). So my proposual is not worse than
a struct, but sometimes helps to get (better) control of which
memory locations are accessed, than struct-s can provide.
If it is only necessary to *read-access* the bytes in question,
the approach described later in my original posting for getting
'wrong' byte order 'right', may also be used in case
of not properly aligned short-s, int-s or long-s.

(%) If a compiler, which supports an option to pack structures,
does this *always tightly*, even on systems with specific alignment
requirements for short-s, int-s and long-s, it may emit code
to acces the LSB/MSB idividual and combine them in a register,
but this would be such an extreme performance penalty, that
I guess such compilers are rare.
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.lang.c mailing list