我在处理一些代码时,看到有人使用了这种模式将字符串连接起来:
sprintf(buffer, "%s <input type='file' name='%s' />\r\n", buffer, id);
sprintf(buffer, "%s</td>", buffer);
我相当确定这不是安全的C代码。你会注意到buffer
既是输出也是第一个输入。
除了缓冲区溢出的明显可能性之外,我认为在函数执行期间没有保证buffer
不会发生更改(即关于restrict
的指定的目标字符串状态在函数执行时不确定)。sprintf的签名还指定了目标字符串是restrict
的。
我还记得有一份关于memcpy中写入推测的报告,并且我看不出为什么某个C库不能在sprintf中做同样的事情。在这种情况下,当然会向其源中写入。那么这种行为是否安全呢?
供参考,我提议:
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);
替换这个。