如果使用错误的格式字符串调用printf,会发生什么? [英] What can happen if printf is called with a wrong format string?

查看:154
本文介绍了如果使用错误的格式字符串调用printf,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Or in other words: Could a wrong printf / fprintf decimal integer (%d, %u, %ld, %lld) format string cause a program to crash or lead to undefined behavior?

Cosinder下面的代码行:

Cosinder following lines of code:

#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位结构上的结果:

Result on 32 bit architecture:

4
4
10, 20


b $ b

64位架构上的结果:

Result on 64 bit architecture:

4
8
10, 20

无论如何,程序打印预期的结果。我知道,如果 long 值超过 int 范围,程序打印错误的数字 - 这是丑陋,

In any case the program prints the expected result. I know, if the long value exceeds the int range, the program prints wrong numbers – which is ugly, but doesn't effect the main purpose of the program –, but beside this, could anything unexpected happen?

推荐答案


如果使用错误的格式字符串调用printf,会发生什么情况?

它是未定义的行为!

未定义的行为意味着任何事情都可能发生。它可能会显示您期望或可能不会或可能会崩溃的结果。

Anything can happen. It is Undefined behavior!
Undefined behavior means that anything can happen. It may show you results which you expect or it may not or it may crash. Anything can happen and you can blame no one but yourself about it.

参考:

c99标准:7.19.6.1:

第9段


如果转换规范无效,行为是未定义的。 225)如果任何参数是
不是相应转换规范的正确类型,行为是
undefined。

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.

这篇关于如果使用错误的格式字符串调用printf,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆