LearnFrenzy
Sign in Take a free test

C Library Functions · Find the Error · Question 2

Error: strcpy into a buffer that is too small Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char city[6];
    strcpy(city, "Bengaluru");
    printf("%s\n", city);
    return 0;
}
  • A strcpy needs a length
  • B "Bengaluru" needs 10 bytes but city has 6, so strcpy writes past the array – a buffer overflow Correct
  • C city must be a pointer
  • D There is no bug
Correct Answer: Option B

strcpy never checks the destination size. Make the array large enough or use snprintf(city, sizeof city, "%s", src), which truncates safely.

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