简体   繁体   English

尝试防止堆栈溢出时出现意外结果

[英]Unexpected results when trying to prevent stack overflow

I'm trying to secure the fields below by specifying the width of the variables so that buffer overflow will not occur. 我试图通过指定变量的宽度来保护下面的字段,以便不会发生缓冲区溢出。 I would prefer not to use fgets() as I am trying to write something within the specifications I have been given (using scanf). 我宁愿不使用fgets(),因为我试图在我给出的规范中写一些东西(使用scanf)。

The code is below: 代码如下:

char firstName[11], surName[21], job[16];

printf("Enter first name: ");
scanf("%10s", firstName);
printf("Enter surname: ");
scanf("%20s", surName);
printf("Enter job: ");
scanf("%15s", job);

So for input like so: 所以对于这样的输入:

Enter first Name: UmbertoOverflow
/*surName gets skipped over*/
Enter job: janitor

I get: 我明白了:

First name: UmbertoOve
Surname: rflow
Job: janitor

It doesn't give me a chance to enter surname, it just fills with the remainder of the first name. 它没有给我一个输入姓氏的机会,它只是填充了名字的其余部分。 This seems to be buffer overflow to me, so is there a way of using scanf without getting this result? 这似乎是缓冲区溢出给我,所以有没有办法使用scanf而不会得到这个结果?

%10s for first name reads only first 10 characters - UmbertoOve - from input string and puts into firstname . 名字的%10s只读取前10个字符 - UmbertoOve - 来自输入字符串并放入firstname The remaining - rflow - are still in the input buffer of program and scanf() for surname takes those characters. 其余- rflow -仍然在节目和的输入缓冲器scanf()用于surname需要这些字符。 '\\n' - or Return - key pressed while entering first name works as terminator and adds rflow in surname . '\\n' - 或Return - key输入名字时按下的Return - key作为终结符并在surname添加rflow

Its not buffer overflow, but expected behavior. 它不是缓冲区溢出,而是预期的行为。

It's not bufferoverflow. 这不是缓冲区溢出。 It's just that scanf takes space or newline as the delimiter. 只是scanf以空格或换行符作为分隔符。 Hence, the first scanf scans for 10 chars and the next continues to scan till it finds a space or '\\n'. 因此,第一个scanf扫描10个字符,然后下一个继续扫描,直到找到空格或'\\ n'。

Use 采用

    scanf("%10s%*s", firstName);
    scanf("%20s%*s", surName);
    scanf("%15s%*s", job);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM