Re: Out-of-bounds nonsense



On Thu, 2 Nov 2006 18:32:21 UTC, Frederick Gotham <fgothamNO@xxxxxxxx>
wrote:

Roberto Waltman:

Not so:

/* in a system where sizeof long is 4 */
long obj1;
char obj2;
/* UB: attempts to copy 3 chars past obj2 */
memcpy(&obj1,&obj2,sizeof obj1);


Of course, you're right.

Type1 obj1;
Type2 obj2;

if (sizeof obj2 >= sizeof obj1)
memcpy(&obj1,&obj2,sizeof obj1);

May result in udefined behavior when Type1 != Type2 as the
representation of different types does not require that they are have
to have the same padding bits adn/or alignment requirements. memcpy
can fail in the lands of udefined behavior here. Accessing obje1
thereafter can end in anything but may not do what you thinks it
should do.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
.



Relevant Pages

  • Re: Out-of-bounds nonsense
    ... Herbert Rosenau: ... representation of different types does not require that they are have ... to have the same padding bits adn/or alignment requirements. ...
    (comp.lang.c)
  • Re: reinitialization an array
    ... memset is only useable on arraays of type char. ... accepts and there is no other type available that can set type int, ... except char can contain padding bits. ... Visit http://www.ecomstation.de the home of german eComStation ...
    (comp.lang.c)