Hacker News 中文摘要

RSS订阅

也不使用strcpy -- No strcpy either

文章摘要

文章指出strncpy()函数设计存在缺陷,如可能不终止目标字符串且会填充零值,建议代码库完全避免使用该函数。作者提到他们已在curl源码中移除了所有strncpy()调用。

文章总结

不再使用strcpy函数

作者Daniel Stenberg在2025年12月29日发表文章,分享了curl项目在字符串处理函数上的改进历程。

背景回顾

  1. 此前curl项目已经移除了所有strncpy()调用,因为这个函数存在设计缺陷:

    • 可能不会在目标缓冲区添加空终止符
    • 会用零填充整个目标缓冲区
    • 大多数情况下都不是理想的选择
  2. 在移除strncpy时,团队确保:

    • 要么完整复制字符串
    • 要么返回错误
    • 特殊情况使用memcpy显式处理空终止符

关于strcpy的问题

虽然strcpy比strncpy更合理,但仍存在风险: - 不指定目标缓冲区或源字符串长度 - 依赖前置的缓冲区大小检查 - 在长期维护中,检查逻辑可能被修改或分离

解决方案

curl引入新的字符串复制函数curlx_strcopyc void curlx_strcopy(char *dest, size_t dsize, const char *src, size_t slen) { DEBUGASSERT(slen < dsize); if(slen < dsize) { memcpy(dest, src, slen); dest[slen] = 0; } else if(dsize) dest[0] = 0; } 特点: - 需要目标缓冲区大小和源字符串长度 - 确保空终止符 - 使用memcpy实现 - 完全禁止strcpy使用

额外好处

这个改动还能减少AI聊天机器人对strcpy使用的误报,虽然它们可能会找到其他问题来报告。

(文章配图展示了curl项目中strncpy和strcpy使用密度的历史变化趋势)

评论总结

评论总结:

  1. 关于AI代码检查的争议:
  • 批评观点:AI对strcpy等函数的检查过于武断,容易产生误报 "strcpy in source code is like a honey pot for generating hallucinated vulnerability claims"(Scubabear68) "Why is this even a thing and isn't opt-in?"(snvzz)
  • 支持观点:AI检查确实帮助发现了大量问题 "fixed several hundred bugs as a direct result of those reports"(stabbels引用Daniel Sternberg)
  1. 关于字符串处理API设计的讨论:
  • 现有C字符串函数存在缺陷 "every one of them seems to have some huge caveat"(t43562) "I don't really think this adds anything over forcing callers to use memcpy"(loeg)
  • 需要更好的字符串库设计 "essential to have a library which records...how much memory is allocated"(t43562) "the destination is truncated...I'm really not sold on that"(zahlman)
  1. 其他技术细节讨论:
  • 函数返回值设计问题 "doesn't return success...clumsy to write but also error prone"(swinglock)
  • 可视化图表改进建议 "could benefit in mobile from using larger fonts"(pama)
  1. 幽默/讽刺评论:
  • 对AI报告准确性的调侃 "LMAO...the initial AI Slop report was right"(TZubiri)
  • 标题的简单评论 "No strcpy either"(senthil_rajasek)