snprintf()函數傳回值“陷阱”

來源:互聯網
上載者:User

 

我最近最佳化一個Linux-C小程式,用snprintf()函數往數組(或字串)裡寫入資料。我不用sprintf()是因為它不夠安全,不小心就會記憶體溢出,導致“段錯誤”!我認識並使用snprintf()很久了,但今天才完全明白了它的傳回值的意思。 函數原型:
int snprintf(char *str, size_t size, const char *format, ...); size 的作用就是限制往str寫入不超過size個位元組(包括了結尾的'\0')。因為sprintf()函數如果成功的話,返回成功寫入的位元組數(字元數),我就一直以為snprintf()函數也是如此,也就是snprintf()函數不會返回大於size的整數。 看下面一段手冊內容: The functions snprintf() and vsnprintf() do not  write  more than size bytes (including the trailing ’\0’). If the output was truncated due to this limit then the return value is the number of  characters (not including the trailing ’\0’) which would
have been written to the final string if enough space had been  available.  Thus,  a  return value  of  size  or more means that the output was truncated.
 如果輸出因為size的限制而被截斷,傳回值將是“如果有足夠空間儲存,所應能輸出的字元數(不包括字串結尾的'\0')”,這個值和size相等或者比size大!也就是說,如果可以寫入的字串是"0123456789ABCDEF"共16位,但是size限制了是10,這樣 snprintf() 的傳回值將會是16
而不是10! 上面的內容還說,如果傳回值等於或者大於size,則表明輸出字串被截斷了(truncated)。 各位~注意啦~  原文地址:http://snailwarrior.blog.51cto.com/680306/152913

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.