Re: pointer conversion




"Richard Tobin" <richard@xxxxxxxxxxxxxxx> wrote in message news:fb9ran$1fap$1@xxxxxxxxxxxxxxxxxxxxxxxxxx
In article <_eidnezKNPZ67EXbnZ2dnUVZ_vShnZ2d@xxxxxxxxxxx>,
Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx> wrote:

M> You will be OK. char is always 1 byte. So casting an arbitrary
M> pointer to a char *, adding an exact multiple of the size of
M> the original type, and casting back is guaranteed to preserve
M> alignment.

I am not so sure about that; would you care to cite C&V, please, if
you claim that it's guaranteed by the standard?

He's wrong: it's not guaranteed. Simple example:

int target = 42;
int *ptr = &target + 1; /* "an arbitrary pointer" */
ptr = (int*)((char*)ptr + sizeof *ptr); /* U.B. */

If the original pointer points at an actual object of its
type (so it's not "arbitrary"), the conversion is safe.

That seems to be excessive pedantry. He said it "preserves
alignment", not that it's legal. Presumably you would deny that
adding 2 to an int preserves it odd/even parity, because you might
choose INT_MAX.

Yes, to be a successful pedant you've got to be absolutely, precisely accurate.

Clearly if the pointer is misaligned, adding sizeof(*ptr) will preserve the (mis) alignment.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm


.



Relevant Pages

  • Re: pointer conversion
    ... Eric Sosman wrote: ... M> the original type, and casting back is guaranteed to preserve ... If the original pointer points at an actual object of its ... alignment", not that it's legal. ...
    (comp.lang.c)
  • Re: pointer conversion
    ... M> the original type, and casting back is guaranteed to preserve ... If the original pointer points at an actual object of its ... adding 2 to an int preserves it odd/even parity, ...
    (comp.lang.c)
  • Re: realloc() implicit free() ?
    ... block size as a request for one byte, and let the alignment mechanisms raise it as they will. ... is therefore suitably aligned for any type (`struct s' in particular), the value can be assigned to any type of pointer, and can then be used to access an object of that type. ... of the Standard can distort its meaning. ...
    (comp.lang.c)
  • Re: struct and union alignment
    ... > a char object requires only 1-byte alignment. ... I see no reason to require same alignment for types void* and char*, ... (Alignment requirements for character types are discussed ... See for yourself: in both cases "pointer ...
    (comp.lang.c)
  • Re: "free space" with declared type (alignment discussion)
    ... >>a function pointer member, a struct pointer member, and maybe a few ... > It doesn't put any extra constraint on alignment beyond this. ... > To assess actual alignment constraints, a structure might be used to figure how ...
    (comp.lang.c)