c - 使用带字符串的长度子说明符的 printf 行为

标签 c printf undefined-behavior libc format-specifiers

我很好奇 printf 是如何工作的,我尝试了很多技巧,比如:

printf("Test 1: %hs\n", "hi");
printf("Test 2: %hhs\n", "hi");
printf("Test 3: %ls\n", "hi");
printf("Test 4: %lls\n", "hi");
printf("Test 5: %js\n", "hi");
printf("Test 6: %zs\n", "hi");
printf("Test 7: %ts", "hi");

我将 printf 与 s 说明符和所有长度修饰符一起使用(通常与数字说明符一起使用(如 d/i/u/o ...)和 i得到奇怪的输出:

Test 1: hi
Test 2: hi
Test 3: Test 4: Test 5: Test 6: hi
Test 7: hi

似乎是 l/ll/j 长度修饰符导致 printf 错误并停止工作(它不打印 \n 但使用所有其他长度修饰符它似乎忽略了长度修饰符并像正常用法一样工作。

为什么会遵循这种行为?

最佳答案

答案是undefined behaviour .格式说明符 %s 不支持您用于传递的参数的任何长度修饰符。 C 中未定义格式说明符不匹配。当我使用 gcc 编译器 (gcc -Wall -Wextra -std=c11 test.c) 编译您的代码时,它表示:

test.c: In function ‘main’:
test.c:5:19: warning: use of ‘h’ length modifier with ‘s’ type character has either no effect or undefined behavior [-Wformat=]
 printf("Test 1: %hs\n", "hi");
                   ^
test.c:6:20: warning: use of ‘hh’ length modifier with ‘s’ type character has either no effect or undefined behavior [-Wformat=]
 printf("Test 2: %hhs\n", "hi");
                    ^
test.c:7:19: warning: format ‘%ls’ expects argument of type ‘wchar_t *’, but argument 2 has type ‘char *’ [-Wformat=]
 printf("Test 3: %ls\n", "hi");
                   ^
test.c:8:20: warning: use of ‘ll’ length modifier with ‘s’ type character has either no effect or undefined behavior [-Wformat=]
 printf("Test 4: %lls\n", "hi");
                    ^
test.c:9:19: warning: use of ‘j’ length modifier with ‘s’ type character has either no effect or undefined behavior [-Wformat=]
 printf("Test 5: %js\n", "hi");
                   ^
test.c:10:19: warning: use of ‘z’ length modifier with ‘s’ type character has either no effect or undefined behavior [-Wformat=]
 printf("Test 6: %zs\n", "hi");
                   ^
test.c:11:19: warning: use of ‘t’ length modifier with ‘s’ type character has either no effect or undefined behavior [-Wformat=]
 printf("Test 7: %ts", "hi");

关于c - 使用带字符串的长度子说明符的 printf 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40595805/

相关文章:

c - 32 位无符号乘法在 64 位上导致未定义的行为?

c - OpenCV:从 harpia 导出源代码后: "too few arguments to function ‘cvHaarDetectObjects’“

c - QueryPerformanceFrequency 与 CPU 速度不匹配?

c++ - 将文件中的整数扫描到 C 中的数组中?

c - C中fprintf的间距

c++ - 引用相同变量的函数参数

c++ - Linux、waitpid、WNOHANG 和僵尸

java - 有没有什么方法可以调用清理函数来清理 native 代码,同时在 Android 中保留任何 Activity ?

c - 为什么我的评估在 C 中无法正确显示?

c++ - 导致未定义行为的悬挂引用