对strlcat的一点探讨.docVIP

  • 8
  • 0
  • 约5.35千字
  • 约 7页
  • 2015-09-26 发布于重庆
  • 举报
对strlcat的一点探讨

http://www.gratisoft.us/todd/papers/strlcpy.html 对两个函数的说明如下: The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that is simply the length of the source; for strlcat() that means the length of the destination (before concatenation) plus the length of the source. To check for truncation, the programmer need only verify that the return value is less than the size parameter. Thus, if truncation has occurred, the number of bytes needed to store the entire string is now known and the programmer may allocate more space and re-copy the strings if he or she wishes. The return value has similar semantics to the return value of snprintf() as implemented in BSD and as specified by the upcoming C9X specification?[4]?(note that not all snprintf() implementations currently comply with C9X). If no truncation occurred, the programmer now has the length of the resulting string. This is useful since it is common practice to build a string with strncpy() and strncat() and then to find the length of the result using strlen(). With strlcpy() and strlcat() the final strlen() is no longer necessary. 也就是说: strlcpy?和?strlcat?函数返回最终创建的字符串长度。对于?strlcpy?来说是源字符串的长度,对于?strlcat?来说意味着目标的长度加源的长度。 为了检查截断,程序员只需验证返回值是否小于?size?参数。因此,如果发生截断,那么根据返回值可以知道总共需要多大的空间才足以放下目标串和源串,此时如果程序员愿意,可以重新分配空间,并重新复制这些字符串。 如果没有截断发生,程序员现在通过返回值获得了最终字符串的总长度;这是有用的,因为通常用?strncpy?和strncat?来构造字符串然后使用?strlen?来取得字符串的长度。使用?strlcpy?和?strlcat,原来作为后续操作的strlen?就不需要了。 以下链接给出了整篇文章的翻译: /517862/112454 翻译得不是很贴切,其中提到“如果发生截断,可以发现已经存储了多少个字节”,原文并未出现类似的说法。阅读原码可以知道,仅仅通过strlcpy和strlcat本身是无法获得已截断的字节数的。 另外一个链接: /help/index.jsp?topic=/com.arm.doc.dui0349bc/CJABDHJJ.html 提到“可以调用一次?strlcat()?以了解需要多少空间,然后分配空间(如果没有足够的空间),最后再次调用?strlcat()?以创建所需的字符串/bugzilla/attachment.cgi?id=91 /tx7do/archive/2009/10/08/98071.html 下面给出源码的运行示例:dst→目标字符串,src1→源字符串1,src2→源字符串2,现在先把src1追加到dst,接着再追加src2,下面给出了整个过程中,dst字符串的变化: 可以看到,追加src1时,dst拥有足够的空间,因而追加操作得以正确执行,并且函数返回ret1=dlen+s1-src1,即目标串长+源串长。继续追加src2,dst尚有空闲空间,然而不足以放

文档评论(0)

1亿VIP精品文档

相关文档