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?
> 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 was char then it might be plausible for ii to be located
immediately following the space allocated for buf in which case the
'\0' at the end of the string being copied may be written to ii making
it's value 0. This is still undefined behavior according to the
Standard though and would be completely implementation dependant.

Is this for a general C class or a compiler construction/assembly/etc
class?

Robert Gamble

.



Relevant Pages

  • Re: low-level question
    ... Darn! ... Why does the following program output a 0? ... If ii is allocated just after the end of buf, and if the platform uses ... a little-endian representation for int, ...
    (comp.lang.c)
  • low-level question
    ... Darn! ... Why does the following program output a 0? ... main(int argc, char *argv) ... char buf[4]; ...
    (comp.lang.c)
  • Re: program is not crashing, after 10 iteration
    ... your code results in undefined behavior. ... Actually, it occurs much earlier, during the first iteration. ... ptr invokes UB. ... On many systems (where int has no trap representations and the ...
    (comp.std.c)
  • Re: I want my segmentation fault!
    ... no occurrences of free and a lot of routines returning pointers to ... int length_of_list; ... This invokes undefined behavior because ml1 has been freed. ... memory is really available for reuse, I'd be glad to know about it. ...
    (comp.lang.c.moderated)
  • Re: pointer to const int
    ... int main ... ..and in fact the former causes undefined behavior. ... it's not an explicit requirement stated normatively in the standard ... terminating new-line character is implementation-defined. ...
    (comp.lang.c)