printf - C: strncpy more characters than allocated then printing... unexpected output? -
in sample code given professor:
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char alpha[] = "abcdefghijklmnopqrstuvwxyz"; printf( "%s\n", alpha ); printf( "%c\n", alpha[8] ); alpha[8] = 'z'; /* segmentation fault if alpha declared statically! */ printf( "%d\n", sizeof( alpha ) ); printf( "%d\n", strlen( alpha ) ); char x[10]; strncpy( x, alpha, 26 ); /* strncpy() not copy or append '\0' */ printf( "%s\n", x ); return exit_success; }
when first compiling , running, program segfaults due to, see in few minutes of googling, gcc protection mechanism against buffer overflows (triggered printf( "%s\n", x );
in x had been filled 26 bytes alpha). believe understand.
however, when disabling protection mechanism gcc -fno-stack-protector, output see is:
abcdefghijklmnopqrstuvwxyz 27 26 abcdefghzjklmnopqrstuvwxyzklmnopqrstuvwxyz
i thought since strncpy not null terminate string, when x
printed might print full value of alpha
- in fact, it's printing of alpha
, , more alpha
!
can provide insight here?
with code:
char x[10]; strncpy( x, alpha, 26 );
you copying 26 bytes of data 10-byte array, means overwriting 16 bytes of whatever memory happened adjacent "x". case looks adjacent "x" "alpha", clobbered part of initial array
when "printf" x, keeps printing until hits null byte, prints out 26 bytes copied, plus whatever else in memory (the surviving contents of "alpha") until next null byte.
Comments
Post a Comment