gpt4 book ai didi

c++ - 如果使用错误的格式字符串调用 printf 会发生什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:52 25 4
gpt4 key购买 nike

或者换句话说:可能是错误的 printf/fprintf 十进制整数 (%d, %u , %ld, %lld) 格式字符串导致程序崩溃或导致未定义的行为?

Coinder 以下代码行:

#include <iostream>
#include <cstdio>

int main() {
std::cout << sizeof(int) << std::endl
<< sizeof(long) << std::endl;

long a = 10;
long b = 20;
std::printf("%d, %d\n", a, b);

return 0;
}

32 位架构的结果:

4
4
10, 20

64 位架构的结果:

4
8
10, 20

在任何情况下,程序都会打印出预期的结果。我知道,如果 long 值超出 int 范围,程序会打印错误的数字——这很丑陋,但不会影响程序的主要目的——但是除此之外,还会有什么意外发生吗?

最佳答案

What can happen if printf is called with a wrong format string?

任何事情都可能发生。这是未定义的行为!
未定义的行为意味着任何事情都可能发生。它可能会显示您期望的结果,也可能不会或可能会崩溃。任何事情都可能发生,除了你自己,你不能责怪任何人。

引用:

c99 标准:7.19.6.1:
第 9 段:

If a conversion specification is invalid, the behavior is undefined.225) If any argument is not the correct type for the corresponding coversion specification, the behavior is undefined.

关于c++ - 如果使用错误的格式字符串调用 printf 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14504148/

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