I'm testing when stack smashing is detected, and I noticed I don't get stack smashing is detected when I write a null character after a char buffer.
In this example, I write characters into a char buffer, and then write the null character at the end (with f-stack-protector):
#include <stdio.h>
int main(int argc, char *argv[])
{
char buf[8];
char c;
printf("Enter a string: ");
int i;
for (i = 0; (c = getchar()) != '\n'; i ) buf[i] = c;
buf[i] = '\0';
printf("string = [%s]\n", buf);
return 0;
}
I noticed that writing 9 characters will give me *** stack smashing detected ***: terminated
as expected, but writing 8 characters does not. If I input 8 characters in this example, wouldn't the null character be written after the buffer and smash the stack?
I tried replacing the null character to writing some other character like 'A' and I will also get stack smashing detected. Is the null character special in this regard, or is this behaviour unexpected?
CodePudding user response:
Your buffer of 8 has only room for 7 characters 1 null terminator. Therefore you invoke undefined behavior if you attempt to write beyond that. The null character isn't special, undefined behavior means that anything can happen, including "the program seems to work fine". See What is undefined behavior and how does it work?
As a side note, any variable storing the result from getchar()
should be declared as int
. This is because getchar()
may return EOF
, which is an int
not a char
. And yes, it is incredibly stupid to standardize a function named getchar()
and have it return an int
, not a char
. The whole of stdio.h
is filled with library design faults and it should therefore be avoided in production-quality code.
CodePudding user response:
Exception with memory are unpredictable, so don't think why they didn't happen.
An error may occur if an attempt is made to access a location outside of the memory range, but it may not be.