3

Here is my minimal example:

#include <stdio.h>
#include <stdarg.h>
#include <string.h>

void print_strings_and_lengths(int count, ...)
{
    va_list ap;

    /* Print strings */
    va_start(ap, count);
    for (int i = 0; i < count; i++) {
        char *s = va_arg(ap, char *);
        printf("%d - %s\n", i, s);
    }

    /* Print string lengths */
    va_start(ap, count); /* Is it okay to call va_start() again without calling va_end()? */
    for (int i = 0; i < count; i++) {
        char *s = va_arg(ap, char *);
        printf("%d - %zu\n", i, strlen(s));
    }
    va_end(ap);
}

int main()
{
    print_strings_and_lengths(3, "apple", "ball", "cat");
    return 0;
}

This code is calling va_start() twice on the same list of variable arguments. The va_end() function is not called between the two calls. Is this code well defined or does it invoke undefined behavior?

2
  • 2
    Do you have a problem with adding va_end before the second va_start? Commented Jan 6, 2020 at 8:08
  • @רועיאבידן I do not have any problem adding va_end() before the second va_start(). Commented Jan 6, 2020 at 8:27

1 Answer 1

3

C11 7.16.1/1:

[...] Each invocation of the va_start and va_copy macros shall be matched by a corresponding invocation of the va_end macro in the same function.

There's no corresponding va_end for both of the va_start calls so the code causes undefined behaviour, with no diagnostic required as the above quote is not part of a Constraint.

Sign up to request clarification or add additional context in comments.

2 Comments

And to be clear, many compilers/platforms do not allocate variable size objects in va_start, but a very few do. If you care about portability, put the va_end calls in.
@GemTaylor Platforms/compilers for which omitting va_end() causes harm are extremely obscure/rare. Although doing so is undefined behaviour per the standard, it is almost certainly never going to cause a problem in practice, because you will almost certainly never port your code to a platform/compiler on which it would.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.