LearnFrenzy
Sign in Take a free test

Variable Number of Arguments · Find the Error · Question 7

Error: using one va_list for two vprintf calls Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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

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

void twice(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    vprintf(fmt, ap);
    vprintf(fmt, ap);
    va_end(ap);
}

int main(void) {
    twice("%d %s\n", 7, "seven");
    return 0;
}
  • A vprintf needs stdout
  • B fmt must be const char []
  • C There is no bug
  • D After the first vprintf the va_list has been consumed (its value is indeterminate); the second call needs a fresh va_start or a va_copy Correct
Correct Answer: Option D

Make a copy before the first use: va_list ap2; va_copy(ap2, ap); vprintf(fmt, ap); vprintf(fmt, ap2); va_end(ap2);.

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