Programming Fundamentals · Interview question

Why is scanf("%s", name) dangerous, and what should you do instead?

A strong answer

%s with no length cap will read characters into the buffer until it hits whitespace, with no upper bound. If name is a char[16] and the user types 100 characters, scanf will write 100 bytes plus a null terminator past the end of name, corrupting whatever sits next to it on the stack. That's the textbook buffer-overflow vulnerability, historically the source of countless security exploits. The defensive form is scanf("%15s", name) (cap at 15 chars + null), or better, use fgets(name, sizeof(name), stdin) which can't overflow because it takes the buffer size as an argument and stops there.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Input & Output

How a program talks to the outside world. printf and scanf in C: format specifiers, common traps, and why the return value matters.

More Input & Output questions

Browse all 472 interview questions