LearnFrenzy
Sign in Take a free test

C Input / Output · Find the Error · Question 3

Error: scanf("%s") into a small array Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below is given the input Alexander. Which statement correctly describes its bug?

main.c
#include <stdio.h>

int main(void) {
    char name[5];
    scanf("%s", name);
    printf("Hello, %s\n", name);
    return 0;
}
  • A name needs an &
  • B %s has no width, so the 9 letters plus '\0' are written past the end of the 5-byte array – a buffer overflow Correct
  • C printf cannot print char arrays
  • D There is no bug
Correct Answer: Option B

Limit the field to the array size minus one: scanf("%4s", name) – or better, read a line with fgets into a larger buffer.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links