When we define a character array as ‘char name[10]’, this indicate that the array ‘name’ can hold a string of length ten character. But in the program shown below the array name can hold more than ten characters. How is this possible?
//print the name of a person.
char name[10];
scanf("%s",name);
printf("%s",name);
Here if I enter a name even of length greater than ten character, there is no run time error and the program prints all the characters I have entered.
There is a program termination if I enter the name of twenty or more characters.
Note: I am running the program on Ubuntu9.04 using a gcc compiler.
scanf allows for a maximum width specifier, as in
This will read up to 9 characters and add a terminating NUL character, for a total of 10 characters.
What happens if you don’t limit the amount of characters scanf can read? Well, then your string ends up overwriting something else. In this case, I guess your buffer is on the stack, so you overwrite something on the stack. The stack holds local variables, return addresses (to the function that called this function), and function arguments. Now, a malicious user could fill that buffer with arbitrary code, and overwrite the return address with the address of that code (there are many variants of this attack). A malicious user could execute arbitrary code through that program.