Re: pointer conversion



Charlton Wilbur wrote:
"M" == Malcolm McLean <regniztar@xxxxxxxxxxxxxx> writes:

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.

--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.



Relevant Pages

  • Re: pointer conversion
    ... 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. ...
    (comp.lang.c)
  • Re: pointer conversion
    ... char is always 1 byte. ... M> pointer to a char *, adding an exact multiple of the size of ... and casting back is guaranteed to preserve ...
    (comp.lang.c)
  • Re: Type casting
    ... >> casting it back to the original type. ... The standard lays out the rules in §5.2.10, ... for different pointer types, ... cast notation need be involved, ...
    (comp.lang.cpp)
  • Re: is const necessary in eg int compar(const void *, const void *)
    ... void *' arguments to assign to a temporary pointer of the appropriate ... avoid casting. ... except that a pointer may be assigned to a _Bool. ... int by_age(const void *vsl, const void *vsr) ...
    (comp.lang.c)
  • Re: Polymorphism
    ... > casting can cause problems with the memory. ... You cannot simply cast a pointer to base to a pointer to derived and ... Converting a pointer to a derived class object to a pointer to base is OK ...
    (comp.lang.cpp)