LearnFrenzy
Sign in Take a free test

C Input / Output · Find the Error · Question 8

Error: sprintf writing into a string literal Answer, explanation & discussion

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

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

main.c
#include <stdio.h>

int main(void) {
    char *msg = "Score: ---";
    sprintf(msg, "Score: %d", 87);
    puts(msg);
    return 0;
}
  • A %d must be %s
  • B msg points to a string literal, which is read-only; writing into it crashes – use an array such as char msg[32] Correct
  • C sprintf returns void
  • D There is no bug
Correct Answer: Option B

String literals may be stored in read-only memory. Format into a buffer you own, and prefer snprintf(msg, sizeof msg, …).

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