为什么sprintf和snprintf的行为是不同的,当我们使用相同的源和目的? [英] why Behavior of sprintf and snprintf is different when we use same source and destination?
问题描述
我有一个简单的code,它使用的sprintf
I have a simple code which uses sprintf
#include <stdio.h>
int main()
{
char str_src [1024]={"Hello"};
sprintf(str_src,"%s%s",str_src,"hiiiiiiiiiii");
printf("result = %s",str_src);
}
我编译时得到正确的结果:
When i compile i get correct result :
结果= Hellohiiiiiiiiiii
result = Hellohiiiiiiiiiii
但由于sprintf的是不安全,我决定改变这snprintf的。我认为这将是非常简单的。我改变的sprintf到的snprintf像下面
But since sprintf is unsecure, i decided to change this to snprintf. I thought it would be really simple. I changed sprintf to snprintf like below
snprintf(str_src,1024,"%s%s",str_src,"hiiiiiiiiiii");
现在如果我编译并运行code,我得到不同的结果。
Now If i compile and run the code, i get different result
结果= hiiiiiiiiiii
result = hiiiiiiiiiii
我面对这个问题,如果我使用str_src作为第四个参数(作为值%S)。它令人惊奇为什么snprintf的行为比sprintf的有什么不同?
I face this problem if i use str_src as 4th parameter (as a value to %s). Its suprising why the behavior of snprintf is different than sprintf?
推荐答案
这是未定义行为的使用相同的缓冲既作为目的地和来源。
It's undefined behavior to use the same buffer both as destination and source.
从C11规范(7.21.6.6/2):
From the C11 specification (7.21.6.6/2):
如果复制操作是重叠的对象之间,行为是不确定的。
If copying takes place between objects that overlap, the behavior is undefined.
同样是说,的snprintf
(7.21.6.5/2),并且也对的va_list
变体好。
The same is said for snprintf
(7.21.6.5/2), and also on the va_list
variants as well.
不幸的是这一切都共同运行code,但它不能真正依靠工作。
Unfortunately it's all to common in running code, but it can't really be relied on to work.
这篇关于为什么sprintf和snprintf的行为是不同的,当我们使用相同的源和目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!