Can we call va_start() twice without calling va_end() in between?

六月ゝ 毕业季﹏ 提交于 2021-01-04 09:20:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/59608636/can-we-call-va-start-twice-without-calling-va-end-in-between

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!