Question

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?

Was it helpful?

Solution

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.

char buffer[30] = {'\0'};
scanf("%29s", buffer);

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".

char buffer[30] = {'\0'};
scanf("%29c", buffer);
buffer[29] = '\0';

OTHER TIPS

From the scanf manual:

s Matches a sequence of non-white-space characters; the next pointer must be a pointer to char, and the array must be large enough to accept all the sequence and the terminating NUL character. The input string stops at white space or at the maximum field width, whichever occurs first.

You are invoking UB. Try:

#define str(x) #x
#define xstr(s) str(x)
#define BUFSIZE 30

char buffer[ BUFSIZE + 1 ];
scanf("%" xstr(BUFSIZE) "s", buf);

To ignore anything beyond BUFSIZE characters suppress assignment:

scanf("%" xstr(BUFSIZE) "s%*", buf);

You should also check if the user has entered return/newline and terminate scanf if he has:

scanf("%" xstr(BUFSIZE) "[^\n]s%[^\n]*", buf);

and it is good practice to check for return values, so:

int rc = scanf("%" xstr(BUFSIZE) "[^\n]s%[^\n]*", buf);

and finally, check if the there's anything left (such as the newline, and consume it):

if (!feof(stdin))
    getchar();

You will have a buffer overrun because you haven't allowed for the terminating NUL character. Declare your buffer like this:

char buffer[31];

and you will be fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top