gpt4 book ai didi

c++ - %n 格式说明符程序在不同的编译器上给出不同的输出。为什么?

转载 作者:IT老高 更新时间:2023-10-28 22:04:43 29 4
gpt4 key购买 nike

我在 this question 阅读了 C 语言中的 %n 格式说明符。 .但是当我在不同的 C++ 编译器上尝试以下程序时,它给了我不同的输出。

为什么?是什么原因?是否发生了未定义或实现定义的行为?

#include<stdio.h>

int main()
{
int c = -1;
printf("geeks for %ngeeks ", &c);
printf("%d", c);
getchar();
return 0;
}

输出:

代码块 13.12:(正确输出)

geeks for geeks 10

Borland/CodeGear/Embarcadero C++:(正确输出)

geeks for geeks 10

奥威尔开发 C++:

geeks -1

Microsoft Visual Studio 2010:

Debug assertion failed ("'n' format specifier disabled",0) 

最佳答案

正如问题中所述,Code Blocks 确实正确,而 Orwell Dev C++ 不正确。另一方面,Visual Studio 是不合格的。

cppreferences C documentation for printf says说:

returns the number of characters written so far by this call to the function.

我在标准草案中没有看到任何使此选项成为可选的内容,C++ 指的是相对于 printf 的 C 标准。 MSDN documents this并说:

Because the %n format is inherently insecure, it is disabled by default. If %n is encountered in a format string, the invalid parameter handler is invoked, as described in Parameter Validation. To enable %n support, see _set_printf_count_output.

为什么 %n 格式本质上是不安全的?

我假设他们认为它不安全是因为 Format String Vulnerability 中概述的安全问题。记录了利用这一点的一种可能方法。它基于由用户输入控制的格式字符串。论文给出了以下例子:

char user_input[100];
scanf("%s", user_input);
printf(user_input);

退休忍者链接到 Bugtraq post它演示了一个在 proftpd 1.2.0pre6 中被利用的漏洞的真实示例:

  • ftp to host
  • login (anonymous or no)

(this should be all on one line, no spaces)

ftp> ls aaaXXXX%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u %u%u%u%u%u%u%u%u%u%653300u%n

(replace the X's with the characters with ascii values 0xdc,0x4f,0x07,0x08 consecutively)

Lots of other nasties can easily be easily done with this. Since proftpd will pass on user input data to snprintf, argument attacks are easy.

Visual Studios 方法的问题在于它破坏了可移植性。其他方法包括使用 Wformat-security used by gcc 等标志。与 -WError 结合使用可能会导致错误,但您可以选择它作为构建过程的一部分。

关于c++ - %n 格式说明符程序在不同的编译器上给出不同的输出。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218872/

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