Re: low-level question



jesso wrote:

> I couldn't get this on a midterm. Darn!
>
> Anyone want to help?
>
> 1. Why does the following program output a 0?

Undefined behavior. strcpy writes five characters into a four-character
buffer ('A'x4, then a 0). Of course, it might not produce a zero. It might
produce a 1, 42, -999, 'ducks? thanks', erase your harddrive, or simply
crash.

In fact, on my system it produces a one with -O1 or higher, so the question
truly is nonsensical.

> 2. Explain in detail.
> 3. How could you prevent this outcome without changing the code?

You can't. With the code as is, it will always invoke undefined behavior. No
wonder you couldn't get this on your midterm; it asks the impossible.

>
>
> #include <stdio.h>
> #include <string.h>
>
> int
> main( int argc, char *argv[] )
> {
> int ii = 1;
> char buf[ 4 ];
Make this: char buf[5];
>
> strcpy( buf, "AAAA" );
Or make the string three characters or less.

>
> printf( "%d\n", ii );
>
> return 0;
> }

--
λz.λi.i(i((λn.λm.λz.λi.nz(λq.mqi))((λn.λz.λi.n(nzi)i)(λz.λi.i(((λn.λz.λi.n
(nzi)i)(λz.λi.i(iz)))zi)))((λn.λz.λi.n(nzi)i)(λz.λi.i(iz)))zi))
.