In a C variadic function, if va_start() has been called on a va_list, is it required to call va_end() before the function returns?
-
AYes
-
BNo
-
COnly on platforms where va_list is a struct
-
DOnly if fewer than two arguments were read
-
ERequired only when mixing float and double
Answer
Correct Answer: Yes
Explanation
Introduction / Context:va_end is the counterpart to va_start in C’s stdarg.h. Although on some implementations va_end may appear to do nothing, the C standard requires its use to allow the implementation to perform any necessary cleanup or state reset for the va_list.
Given Data / Assumptions:
- va_list ap has been initialized by va_start.
- The function will return normally or via a branch.
Concept / Approach:Once you call va_start, the program has entered a region where the runtime may have reserved resources or needs to restore internal state. Calling va_end signals that iteration is finished. This is required even if you ended up reading zero variadic arguments after initialization.
Step-by-Step Solution:va_list ap; va_start(ap, last_named_param);// zero or more calls to va_arg(ap, type)va_end(ap); // always before return
Verification / Alternative check:Inspect the standard library’s v* functions or compiler documentation—each stresses the contract: every va_start must be paired with a va_end, similar to resource acquisition/cleanup patterns.
Why Other Options Are Wrong:Conditioning va_end on platform, number of arguments, or types is incorrect. The rule is unconditional in portable C code.
Common Pitfalls:Returning early without calling va_end on all paths; using va_list after va_end, which is undefined behavior.
Final Answer:Yes