Re: Does casting lvalue lead to Undefined Behaviour ?
- From: "Harald van Dijk" <truedfx@xxxxxxxxx>
- Date: 28 Dec 2006 22:23:27 -0800
p_cricket_guy@xxxxxxxxxxx wrote:
Please see the code below
-- start listing is_it_ub.c --
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
unsigned char buff[20];
unsigned int i;
i = 0xaabbccddUL;
*((int *)buff) = i; /* Is this UB ? */
Yes. There is no guarantee that buff is correctly aligned for an int.
You can either use memcpy(), or access the representation via (unsigned
char *) &i.
In theory, it's also possible that sizeof(int) is greater than 20,
which will cause obvious problems, but that's not likely to happen in
practice.
printf("buff: %x:%x:%x:%x\n", buff[0], buff[1], buff[2], buff[3]);
This assumes that an int is four bytes. This is not necessarily true,
and in this case the problem does occur in practice.
return EXIT_SUCCESS;
}
-- end listing --
Output:
buff: dd:cc:bb:aa
Output seems correct on my Little Endian PC.
In the statement: "*((int *)buff) = i; ", buff is casted to be treated
as an int *. Is this valid?
My compiler does not produce any diagnostics for the above
program but somebody else complained that their compiler
warns "casting of lvalue is deprecated".
That warning refers to an implementation-specific extension which
you're not using, so don't worry about that.
.
- References:
- Does casting lvalue lead to Undefined Behaviour ?
- From: p_cricket_guy
- Does casting lvalue lead to Undefined Behaviour ?
- Prev by Date: Re: c / c++ : is it end of era ?
- Next by Date: Re: Segment
- Previous by thread: Does casting lvalue lead to Undefined Behaviour ?
- Next by thread: Re: Does casting lvalue lead to Undefined Behaviour ?
- Index(es):
Relevant Pages
|