Difficulty: Easy
Correct Answer: Error: ptr has to be set at begining
Explanation:
Introduction / Context:
Correct sequencing of varargs macros is crucial. The lifetime of a va_list begins with va_start, continues through one or more va_arg calls, and ends with va_end. Skipping va_start results in undefined behavior when attempting to read arguments.
Given Data / Assumptions:
void varfun(int n, ...).va_list ptr; declared but not initialized.va_arg(ptr, int) is called immediately.
Concept / Approach:va_start(ptr, n) initializes ptr so it points just past the last fixed parameter n. Only after this initialization may the code legally use va_arg to read each successive argument. Without initialization, ptr has an indeterminate value, and dereferencing it via va_arg is undefined.
Step-by-Step Solution:
Add va_start(ptr, n); before the first va_arg.Use num = va_arg(ptr, int); to fetch the first promoted integer.After finishing, call va_end(ptr); to clean up.
Verification / Alternative check:
Compilers with warnings enabled often flag missing va_start. Runtime sanitizers may catch crashes or misreads that arise from uninitialized va_list.
Why Other Options Are Wrong:
ptr must be type of va_list — it already is. invalid access to list member is vague; the concrete root cause is the missing initialization. No error is incorrect, as behavior is undefined.
Common Pitfalls:
Forgetting va_end after finishing, and mixing types without a controlling count or format descriptor.
Final Answer:
Error: ptr has to be set at begining
Discussion & Comments