scanf not to exceed buffer overrun

江枫思渺然 提交于 2019-12-06 04:59:57

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

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.

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