I have a buffer and I don’t want the user to enter more characters than the buffer can hold (to avoid a buffer overrun).
I am using scanf and have done like this:
char buffer[30] = {'\0'};
scanf("%30s", buffer);
However, I know I am protected if the user enters more than 30. However, if the user enters more than 30, will the buffer be null terminated?
scanf()with a “%s” conversion specifier adds a terminating null character to the buffer.But, you’re asking for 30 characters, which really means 31 and only have space for 30. You should use a maximum field width of 29.
Also note that the conversion specifier
"%c"works pretty much like"%s", but does not add the terminating null character and does not discard space from the input. Depending on what you expect, it might be better than using “%s”.