-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
I couldn't get this on a midterm. Darn!
Anyone want to help?
1. Why does the following program output a 0?
The program does not /necessarily/ output a 0. The program invokes
undefined behaviour, and /any/ output (or lack of output) is valid.
buf is defined as an array of 4 characters (char buf[4]
However, the program uses the standard function strcpy() to modify the
contents of this array. The string given to strcpy() to copy into buf
consists of 4 characters, /plus/ a string-termination character of \0.
When strcpy() copies the initialization string into buf, it will copy 4
characters (which will fit into buf, as buf is defined as a 4 character
array), and will terminate the copied string with a \0 character. This
terminating character will not fit within the confines of buf (which is
already full), and will be written to some other area of memory.
Assuming specific environmental and compiler characteristics, this \0
character /may/ be written in such a manner as to overwrite the
significant bits of the ii variable, setting ii to 0.
*However*, there is no guarantee that this can happen. It would require
- - ii to start /immediately/ after buf in memory, and
- - ii to be stored as a 'little-endian' binary value
There is no guarantee, from the code and details provided, that the
compiler will
- - align ii to a 4-byte boundary,
- - order ii to /follow/ buf in memory, or
- - store int values as little-endian binary numbers
3. How could you prevent this outcome without changing the code?
Don't run the program.
#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;
}
- --
Lew Pitcher, IT Specialist, Enterprise Data Systems
Enterprise Technology Solutions, TD Bank Financial Group
(Opinions expressed here are my own, not my employer's)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)
iD8DBQFDFFRJagVFX4UWr64RAgk8AJ90VvPuywZWEnLXgjgDM0bd/udhRQCgvu3U
+cNqEFIlcQbqc1J8T1BxITo=
=Jp1t
-----END PGP SIGNATURE-----