Re: low-level question
- From: "Robert Gamble" <rgamble99@xxxxxxxxx>
- Date: 30 Aug 2005 14:03:04 -0700
Keith Thompson wrote:
> "Robert Gamble" <rgamble99@xxxxxxxxx> writes:
> > jesso wrote:
> >> I couldn't get this on a midterm. Darn!
> >>
> >> Anyone want to help?
> >>
> >> 1. Why does the following program output a 0?
> >> 2. Explain in detail.
> >> 3. How could you prevent this outcome without changing the code?
> >>
> >>
> >> #include <stdio.h>
> >> #include <string.h>
> >>
> >> int
> >> main( int argc, char *argv[] )
> >> {
> >> int ii = 1;
> >> char buf[ 4 ];
> >>
> >> strcpy( buf, "AAAA" );
> >>
> >> printf( "%d\n", ii );
> >>
> >> return 0;
> >> }
> >
> > It is undefined behavior in C because you are writing past the end of
> > an arry ("AAAA" is 5 characters, buf is 4). Since it is undefined
> > behavior, anything can happen. There might be certain behaviors that
> > are more likely to occur than others due to nuances of your specific
> > platform but I can't think of anything plausible that would account for
> > the behavior suggested by the question.
>
> If ii is allocated just after the end of buf, and if the platform uses
> a little-endian representation for int, the '\0' of "AAAA" could
> plausibly be written over the low-order byte of ii, causing it to be
> set to 0.
Yep, I was being a little bit narrow-minded when I posted that. I
realized this shortly after I posted and then saw that Lew Pitcher
covered this case so I didn't feel the need to amend my post.
Robert Gamble
.
- References:
- low-level question
- From: jesso
- Re: low-level question
- From: Robert Gamble
- Re: low-level question
- From: Keith Thompson
- low-level question
- Prev by Date: Re: Why C/C++ errors are SO obscure/devious??
- Next by Date: Re: while (1) vs. for ( ;; )
- Previous by thread: Re: low-level question
- Next by thread: Re: low-level question
- Index(es):
Relevant Pages
|