santosh wrote:
>
> jt wrote:
>
> > here is a program..
> > struct st
> > {
> > char ch[3];
> > int a;
> > }st_var={"ABC",68};
>
> Undefined behaviour. You are writing past the bounds of an object, in
> this case 'ch'.
Are you sure? I thought this was perfectly valid:
char chr[3] = "ABC";
In this case, it's simply shorthand for:
char chr[3] = { 'A', 'B', 'C' };
[...]
> > printf("%s",st_var.ch);
This is where UB is invoked, as ch_var.ch is not a nul-terminated
string.
[...]
> > If there is continuous allocation then the output will be
> >
> > ABCD
>
> Only for the ASCII encoding.
And only on little-endian systems.
> > now...suppose tht the memory is not allocated continuously..
> > the first 3 bytes are allocated at 1 place and next 2 bytes are
> > allocated at other place
> > wht will be the output....???
>
> Why are you interested in pathological and broken code? If you want to
> understand the machine at the byte level, maybe you should try assembly
> language.
>
> printf will print all character values starting at the address allocated
> for st_var.ch and will do so until it encounters a null character. But
> strictly according to the standard undefined behaviour is invoked by
> your program so anything could be it's result.
>
> Did you run it and see?
I think a better, and non-UB-invoking form of the question he really
is asking would be:
Are padding bytes within a struct guaranteed to be initialized
to zero?
Of course, you're not actually allowed to use those bytes AFAIK,
so I'm not sure why one needs to be concerned about their value.
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody |
www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net |
www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <private.php?do=newpm&u=>