gpt4 book ai didi

c++ - 逐个处理va_list

转载 作者:太空狗 更新时间:2023-10-29 20:54:05 33 4
gpt4 key购买 nike

以下程序在 64 位 Linux 机器上运行,但在 32 位 Linux 机器上崩溃。

#include <cstdarg>
#include <iostream>

void proc_int(std::va_list va)
{
std::cout << va_arg(va, int);
}

void proc_str(std::va_list va)
{
std::cout << va_arg(va, const char*);
}

void outputv(std::va_list va)
{
proc_int(va);
std::cout << " ";
proc_str(va);
std::cout << "\n";
}

void output(int dummy, ...)
{
va_list va;
va_start(va, dummy);
outputv(va);
va_end(va);
}

int main()
{
output(0, 42, "hello");
}

我认为这是因为 va_list 在 32 位上是 char* 而在 64 位上是 struct __va_list_tag[1]。我可以做哪些更改以使该程序可移植,最好不更改 outputv 的签名?

最佳答案

来自 cppreference ,

If a va_list instance is created, passed to another function, and used via va_arg in that function, then any subsequent use in the calling function should be preceded by a call to va_end

尚不完全清楚(后续使用)是否包括传递给另一个函数,但这肯定是合理的。

检查本地 (Linux) 手册页以进行比较:

If ap [the va_list] is passed to a function that uses va_arg(ap,type) then the value of ap is undefined after the return of that function

所以您根本不允许传递 va_list 并按照您的方式使用它,而 32 位版本恰好可以摆脱它。

What changes can I make to make this program portable, preferably without changing the signature of outputv?

好吧,只是不要将 va_list 传递给其他函数并期望它在之后仍然有效:

void outputv(std::va_list va)
{
std::cout << va_arg(va, int);
std::cout << " ";
std::cout << va_arg(va, const char *);
std::cout << "\n";
}

关于c++ - 逐个处理va_list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40403677/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com