In said:
(e-mail address removed) (Dan Pop) writes: [...]
How do you check that the pointer is aligned for an integer access?
If it isn't, how do you align it?
Non-portably, of course.
Conversions between pointers and integers provide a fairly portable way
(not absolutely portable, of course) that is also blessed by the C
standard (no extensions are needed at all). It works on most hosted
implementations in current use and you'll have to resort to things like ^^^^^^^^^^^^^^
AS/400 for exceptions.
Or Cray vector systems.
Are they still "in current use"?
Yes. We don't have any at SDSC, but I have accounts on a couple of
SV1s at other sites.
It's a quality of implementation issue: if the conversions can be
meaningfully supported, the implementors do the right thing. And on most
hosted implementations *in current use* the conversions are as trivial as
conversions between char pointers and void pointers: a bit pattern is
given a different type.
Conversions between pointers and integers are just reinterpretations
of bit patterns on Cray vector systems too, which means you're going
to shoot yourself in the foot if you treat the result as if it were an
index into a byte array.
(A reminder for those just tuning in: on a Cray vector system, a
machine address points to a 64-bit word. The C compiler uses
CHAR_BIT==8 for compabitility. A char* pointer consists of a word
pointer with a byte offset in the otherwise unused high-order 3 bits;
byte accesses are handled in software.)
Certainly the vast majority of hosted implementations incurrent use
aren't AS/400s, Cray vector systems, or anything else as exotic. But
my guess is that systems on which a char* converted to an integer
can't be tested for alignment by examining the low-order bits are
roughly as common as systems on which a null pointer is something
other than all-bits-zero. I wouldn't use memset() to set a bunch of
pointers to null unless I had a very good reason, and I'd carefully
document that the code is non-portable. I wouldn't use the low-order
bits of the result of a pointer-to-integer conversion to check the
pointer's alignment unless I had a very good reason, and I'd carefully
document that the code is non-portable.
I'm not arguing against non-portable code, but it's important to
recognize that it's non-portable, even if it works on 99.9% of current
systems.
I suspect we're actually in agreement on most or all of this.