문제

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?

도움이 되었습니까?

해결책

%10s for first name reads only first 10 characters - UmbertoOve - from input string and puts into firstname. The remaining - rflow - are still in the input buffer of program and scanf() for surname takes those characters. '\n' - or Return - key pressed while entering first name works as terminator and adds rflow in surname.

Its not buffer overflow, but expected behavior.

다른 팁

It's not bufferoverflow. It's just that scanf takes space or newline as the delimiter. Hence, the first scanf scans for 10 chars and the next continues to scan till it finds a space or '\n'.

Use

    scanf("%10s%*s", firstName);
    scanf("%20s%*s", surName);
    scanf("%15s%*s", job);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top