一个小bug让我发现了sprintf有复制重叠问题

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()目标字符数组不能和格式参数列表中的参数指向同一地址,否则可能发生复制重叠,以前没发现只是没加格式控制符的时候是正常工作的,但这次加了些格式控制符才发现.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值