2
  #include <stdio.h>
  void wrapperPrint(char* s)
  {
      printf(s);
      return;
  }

  int main()
  {

          wrapperPrint("Hello world\n");
          wrapperPrint("This is a string");

      return 0;
  }

如果程序正确打印字符串(确实如此,在 gcc 4.6.3 上测试过),为什么我们需要像 %d、%s 等格式说明符。或者换句话说,这个程序的潜在问题是什么。

4

4 回答 4

6

As-is, there's no problem at all. If, however, you pass in a string containing a percent-sign, that could cause a problem, because printf would try to treat it as the beginning of a conversion specifier, but 1) the rest of the conversion specifier probably won't be there, and 2) you won't have passed a matching argument when you call printf either, so if you do pass a proper conversion specifier, it'll try to use a nonexistent argument (giving undefined behavior).

于 2012-06-20T04:46:24.170 回答
4

为什么我们需要 %d、%s 等格式说明符?

printf不是格式安全的。t 本身不理解类型,您必须明确告诉数据参数printf的格式(类型)。它告诉print您希望如何将参数解释为,如果您不理解,它只会将其视为字符串(如在您的示例代码中)。

请注意,如果格式说明符和实际数据类型不匹配,那么您得到的是Undefined Behavior

于 2012-06-20T04:46:46.393 回答
2

你应该使用 puts(),或者使用 printf("%s", s);

如果格式字符串恰好包含 %s 或任何其他格式,则 printf 将尝试读取您未传递的参数,尝试访问随机的内存块,但结果未定义。

尝试使用传入的 %s 运行您的程序,看看会发生什么。然后尝试在valgrind下再次运行它,以真正看到正在发生的可怕事情。

于 2012-06-20T04:47:04.417 回答
1

There is nothing that mandates the use of format specifier in printf. Rather, it is because you want to print string according to some format that you use printf. You may use other methods (puts) to output plain string.

For the program above, if there are format specifiers in the string, the program will print garbage, since you will still be calling printf underneath.

于 2012-06-20T04:43:07.843 回答