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?

It is an accident. It could return anything. Buffer overflows don't result in well-defined behavior.


2. Explain in detail.

See above.

3. How could you prevent this outcome without changing the code?

You can't fix code without changing it. What are you smoking? A minimum change to the code (not allowed by the conditions) is to declare
char buf[5]; /* Those spaces around '4' seem to be a clue. */


[broken code follows]


#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;
}

.



Relevant Pages