scanf not to exceed buffer overrun

有些话、适合烂在心里 提交于 2019-12-08 02:58:12

问题


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?


回答1:


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';



回答2:


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();



回答3:


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.



来源:https://stackoverflow.com/questions/1721073/scanf-not-to-exceed-buffer-overrun

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!