我看到使用這種模式來連接到在一些代碼字符串我工作:sprintf(buffer,「%s [...]」,buffer,[...])是否安全?
sprintf(buffer, "%s <input type='file' name='%s' />\r\n", buffer, id);
sprintf(buffer, "%s</td>", buffer);
和我相當肯定它不是安全C.你會發現buffer
既是輸出和第一個輸入。
除了很明顯的緩衝區溢出的可能性,我相信不能保證緩衝區不會在函數的開始和結束之間發生變化(即,不能保證什麼狀態的緩衝區將在執行該功能期間)。 sprintf的簽名額外指定目標字符串爲restrict
ed。
我還記得一個speculative writing in 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);
替換此。
即使它*安全*(不會崩潰等)我可以想象它產生的結果不是預期的結果。 – 2009-08-16 03:08:58
@AndrewMedico那是怎麼回事? – cat 2016-09-27 21:49:56