0

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

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?

4

2 回答 2

1

这不是缓冲区溢出。只是 scanf 以空格或换行符作为分隔符。因此,第一个 scanf 扫描 10 个字符,下一个继续扫描,直到找到空格或 '\n'。

利用

    scanf("%10s%*s", firstName);
    scanf("%20s%*s", surName);
    scanf("%15s%*s", job);
于 2013-09-19T08:16:29.583 回答
1

%10sfor first name 仅从UmbertoOve输入字符串中读取前 10 个字符并放入firstname. 剩下的 - rflow- 仍然在程序的输入缓冲区中,并scanf()用于surname获取这些字符。'\n'- 或Return - key在输入名字时按下作为终止符并添加rflow.surname

它不是缓冲区溢出,而是预期的行为。

于 2013-09-19T08:13:31.073 回答