c - snprintf 缓冲区大小的负/零值

标签 c printf buffer

如果将负数或 0 作为第二个参数传递给 snprintf(),它将写入提供的缓冲区位置。希望认为这不应导致任何意外行为。

int snprintf(char *str, size_t size, const char *format, ...);

最佳答案

引用 C11 , chpater §7.21.6.5, snprintf()函数

int snprintf(char * restrict s, size_t n,const char * restrict format, ...);

[...] If n is zero, nothing is written, and s may be a null pointer.

因此,如果您传递 0,则不会写入任何内容。

万一你通过了 - ve 值,它可能会产生问题,因为第二个参数的类型为 size_t这是 unsigned .因此,带符号的值将被视为 unsigned产生不需要的尺寸。这可能会导致问题(内存溢出),因为大小可能超过提供的缓冲区可以处理的大小,这会调用 undefined behavior。 . .尽管如此,只要缓冲区大到足以容纳提供的数据,提供的数据就会写入缓冲区。

来自 §7.19,<stddef.h>

size_t
which is the unsigned integer type of the result of the sizeof operator;

关于c - snprintf 缓冲区大小的负/零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37432797/

相关文章:

javascript - 从服务器发送媒体流到客户端

TCP 窗口和缓冲区 - 检查我的理解?

c - 如何取任何整数,例如 10050,并将其输出为 $100.50?

.net - 加快 IIS/.NET/LINQ 从网络缓冲区检索数据的速度

c - 为什么这部分会出现段错误?

c - 程序中同时使用puts()、gets()、getchar()、putchar()函数

c - C中重叠对象的语义是什么?

java - 如何生成所有矩阵乘法顺序组合

c# - .net 有免费的 printf 实现吗?

c - 使用 fprintf 时,我在输出中得到镜像的字符数组