- 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尚有空闲空间,然而不足以放
您可能关注的文档
- 奈米生医期末考考题.doc
- 奖学金中英文对照.doc
- 奥巴马政府的网络安全战略分析.pdf
- 奖项比赛名称的中英文翻译.doc
- 奥氏体不锈钢管子管板焊接熔敷顺序的研究.pdf
- 奥鹏福建师范【大学英语一】在线作业一二,答案在末尾.doc
- 女性生殖系统解剖生理.doc
- 奶牛产奶量与乳成分的多元回归分析.pdf
- 奶制品加工计划的设计模型.pdf
- 好听的中英文歌推荐.doc
- 全过程工程管理造价咨询工程监理项目服务方案投标方案(技术部分).doc
- 招标代理服务投标技术服务方案(技术方案).doc
- AI大模型与AIGC技术在公安领域的应用解决方案(99页 PPT).pptx
- 工业4.0智能制造数字工厂规划方案.pptx
- 树立社会主义核心价值观.docx
- 三年(2023-2025)中考历史真题分类汇编(全国)专题21 科技文化与社会生活(解析版).docx
- 2025年中考道德与法治真题完全解读(吉林卷).pdf
- 2025年中考道德与法治真题完全解读(安徽卷).pdf
- 三年(2023-2025)中考历史真题分类汇编(全国)专题14 人民解放战争(解析版).pdf
- 三年(2023-2025)广东中考历史真题分类汇编:专题03 中国近代史(八年级上册)(解析版).docx
最近下载
- 500t吊车性能表(中文版).pdf VIP
- 人教版八年级上历史知识点总结 .doc VIP
- 米莉的帽子变变变精品解析.ppt VIP
- 职业教育人工智能应用发展报告(2024-2025).pptx VIP
- 2025年高等教育医学类自考-03037药用植物学考试近5年真题集锦(频考类试题)带答案.docx VIP
- TCAQ10201-2024质量管理小组活动准则_可搜索.pdf VIP
- 确定肿瘤的重要基因信息——提取基因图谱信息方法的研究.pdf VIP
- 事业单位嫖娼违法写检讨书.docx VIP
- 人教版物理8年级下册全册教学课件.pptx
- 第二十五章+图形的相似(复习课件)数学冀教版九年级上册.pptx VIP
原创力文档

文档评论(0)