我看到在我正在处理的一些代码中使用这种模式连接到一个字符串:
sprintf(buffer, "%s <input type='file' name='%s' />\r\n", buffer, id);
sprintf(buffer, "%s</td>", buffer);
我相当肯定它是不安全的 C。你会注意到buffer
它既是输出又是第一个输入。
除了缓冲区溢出的明显可能性之外,我相信不能保证缓冲区在函数的开始和结束之间不会改变(即,不能保证缓冲区的状态在函数的执行)。sprintf 的签名还指定目标字符串是restrict
ed。
我还记得一篇关于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);
替换这个。