gpt4 book ai didi

c - snprintf() 溢出指定长度

转载 作者:太空宇宙 更新时间:2023-11-04 06:18:56 26 4
gpt4 key购买 nike

我正在编写自己的 ncurses 库,突然发现在 GDB 中 snprintf() 返回的长度大于我指定的长度。这是定义的行为还是我的一些错误? (可重现的)片段代码是这样的:

niko: snippets $ cat snprintf.c
#include <unistd.h>
#include <stdio.h>

char *example_string="This is a very long label. It was created to test alignment functions of VERTICAL and HORIZONTAL layout";

void snprintf_test(void) {
char tmp[72];
char fmt[32];
int len;
unsigned short x=20,y=30;

snprintf(fmt,sizeof(fmt),"\033[%%d;%%dH\033[0m\033[48;5;%%dm%%%ds",48);
len=snprintf(tmp,sizeof(tmp),fmt,y,x,0,example_string);
write(STDOUT_FILENO,tmp,len);
}


int main(void) {
snprintf_test();
}
niko: snippets $

现在我们使用调试信息编译并运行:

niko: snippets $ gcc -g -o snprintf snprintf.c
niko: snippets $ gdb ./snprintf -ex "break snprintf_test" -ex run
.....
Reading symbols from ./snprintf...done.
Breakpoint 1 at 0x40058e: file snprintf.c, line 10.
Starting program: /home/deptrack/depserv/snippets/snprintf

Breakpoint 1, snprintf_test () at snprintf.c:10
10 unsigned short x=20,y=30;
Missing separate debuginfos, use: dnf debuginfo-install glibc-2.22-16.fc23.x86_64
(gdb) s
12 snprintf(fmt,sizeof(fmt),"\033[%%d;%%dH\033[0m\033[48;5;%%dm%%%ds",48);
(gdb) print sizeof(fmt)
$1 = 32
(gdb) print sizeof(tmp)
$2 = 72
(gdb) s
13 len=snprintf(tmp,sizeof(tmp),fmt,y,x,0,example_string);
(gdb) print fmt
$3 = "\033[%d;%dH\033[0m\033[48;5;%dm%48s\000\000\000\000\000"
(gdb) print example_string
$4 = 0x4006c0 "This is a very long label. It was created to test alignment functions of VERTICAL and HORIZONTAL layout"
(gdb) s
14 write(STDOUT_FILENO,tmp,len);
(gdb) print len
$5 = 124
(gdb) print sizeof(tmp)
$6 = 72
(gdb)

程序在字符串末尾输出垃圾。如您所见,从 snprintf() 返回的 len 变量表明函数打印的大小超过了允许的大小 72。这是错误还是我的错误?如果定义了此行为,那么为什么 snprintf() 文档说它最多打印 n 个字符。非常具有误导性和错误倾向的声明。我将不得不编写自己的 snprintf() 来解决这个问题。

最佳答案

实际上(来自“man snprintf”):

If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available.

关于c - snprintf() 溢出指定长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39690281/

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