show code:
/*
file name:demo.c
system:ubuntu 20.04
compile command:gcc -std=c99 demo.c
*/
#include<stdio.h>
#include<stddef.h>
int main(){
char str[255]="My name is Li"; /*length of string is 13*/
int num=123456;
printf("%14s.%d\n",str,num); /*output: My name is Li.123456*/
snprintf(str,sizeof(str),"%14s.%d\n",str,num); /*If it is 13, it will output normally*/
printf("%s",str); /*output: .123456*/
}
可以看出同样的格式字符串和对应的参数列表,只是printf的输出目标是stdout,sprintf的输出目标是字符数组,但是产生的输出就不一样.
为什么呢?
查了很多相关网页都没有解释,看来不常遇到,那就执行linux命令:man snprintf
其中有一段:
C99 and POSIX.1-2001 specify that the results are undefined if a call to sprintf(),snprintf(), vsprintf(), or vsnprintf() would cause copying to take place between objects that overlap (e.g., if the target string array and one of the supplied input arguments refer to the same buffer). See NOTES. |
---|
C99和POSIX.1-2001指定如果调用sprintf(), snprintf()、vsprintf()或vsnprintf()会导致对象之间发生复制重叠(例如,如果目标字符串数组和提供的一个输入参数指向 相同的缓冲区)。 详看注释说明. |
可以看到sprintf(),snprintf(),vsprintf(),vsnprintf()目标字符数组不能和格式参数列表中的参数指向同一地址,否则可能发生复制重叠,以前没发现只是没加格式控制符的时候是正常工作的,但这次加了些格式控制符才发现.