可以在调用va_end()之前两次调用va_start()吗?

huangapple go评论52阅读模式
英文:

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

问题

这段代码在同一可变参数列表上两次调用了 va_start() 函数,并且没有在这两次调用之间调用 va_end() 函数。这样的做法会导致未定义行为。

英文:

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

得分: 2

C11 7.16.1/1:

> [...] va_startva_copy 宏的每次调用都应在同一函数中有相应的 va_end 宏的匹配调用。

这两个 va_start 调用都没有相应的 va_end,因此代码会导致未定义的行为,不需要诊断,因为上述引用不是一个约束的一部分。

英文:

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.

huangapple
  • 本文由 发表于 2020年1月6日 16:07:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定