是的sprintf(缓冲,"%S [...]&QUOT ;,缓冲,[...])安全吗? [英] Is sprintf(buffer, "%s […]", buffer, […]) safe?

查看:276
本文介绍了是的sprintf(缓冲,"%S [...]&QUOT ;,缓冲,[...])安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到使用这种模式来连接到一些code我工作的一个字符串:

I saw use of this pattern to concatenate onto a string in some code I was working on:

sprintf(buffer, "%s <input type='file' name='%s' />\r\n", buffer, id);
sprintf(buffer, "%s</td>", buffer);

和我相当肯定它不是安全的C.你会发现,缓存既是输出和第一个输入。

and I'm fairly certain it's not safe C. You'll notice that buffer is both the output and the first input.

除了一个缓冲区溢出的明显的可能性,我相信没有保证缓冲区不会被启动和功能的末端之间改变(即没有保证的到什么缓冲器的状态将是该函数的执行)期间。的sprintf的签名还指定目标字符串限制编辑。

Apart from the obvious possibility of a buffer overflow, I believe there is no guarantee that buffer doesn't get changed between the start and the end of the function (i.e., there is no guarantee as to what the state of buffer will be during the execution of the function). The signature of sprintf additionally specifies that the target string is restricted.

我还记得在memcpy的一个投机性写作的报告,我看不出有任何理由为什么有些C库可能会做同样的事情在一个sprintf的。在这种情况下,当然,将它写入到它的来源。因此,是这种行为的安全?

I also recall a report of a speculative writing in memcpy, and I see no reason why some C library might do the same thing in a sprintf. In this case, of course, it would be writing to its source. So is this behaviour safe?

仅供参考,我建议:

char *bufEnd = buffer + strlen(buffer);
/* sprintf returns the number of f'd and print'd into the s */
bufEnd += sprintf(bufEnd, " <input type='file' name='%s' />\r\n", id);

来代替这一点。

推荐答案

从<一个href=\"http://www.gnu.org/software/libc/manual/html%5Fmono/libc.html#Formatted-Output-Functions\">glibc sprintf的()文档

此函数的行为是
  未定义如果复制发生
  对象之间的重叠换
  举例来说,如果s被给出作为
  控制要打印的说法
  的%s的转换。

The behavior of this function is undefined if copying takes place between objects that overlap—for example, if s is also given as an argument to be printed under control of the ‘%s’ conversion.

有可能是在一个特定的实施安全的;但你不能指望它是便于携带。

It may be safe in a particular implementation; but you could not count on it being portable.

我不知道,你的建议将在所有情况下是安全的两种。你可能仍然是重叠的缓冲区。这晚,我的妻子是如此迷恋我,但我认为你还是可以有情况下要在连接字符串重新使用原来的字符串并覆盖空字符等sprintf的实现可能不知道所使用的重字符串结尾。

I'm not sure that your proposal would be safe in all cases either. You could still be overlapping buffers. It's late and my wife is buggin me but I think that you could still have the case where you want to use the original string again in the concatenated string and are overwriting the null character and so the sprintf implementation might not know where the re-used string ends.

您可能只是想坚持一个snprint()到一个临时缓冲区,然后strncat函数()到它原来的缓冲区。

You might just want to stick with a snprint() to a temp buffer, then strncat() it onto the original buffer.

这篇关于是的sprintf(缓冲,&QUOT;%S [...]&QUOT ;,缓冲,[...])安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆