(评论)
(comments)

原始链接: https://news.ycombinator.com/item?id=43387334

Hacker News上的一篇博客文章讨论了在C语言中实现“愚蠢的智能指针”,引发了热烈讨论。评论者强烈反对这种方法,因为它存在可移植性和安全问题,C语言本身就存在内存不安全的问题。经验丰富的C程序员推荐了替代方案: * 使用`__attribute__((cleanup))`(GCC和Clang可用,有望成为C标准的一部分),例如systemd项目中所用。 * 使用内存池分配器,例如Samba的talloc或Apache的APR。 不推荐使用引用计数,因为它可能导致bug,并且与现代CPU架构不兼容。一位评论者指出,讨论的“智能指针”方法可能会导致分支预测错误,因为这与现代CPU处理返回地址的方式有关。另一位评论者指出,栈保护cookie也可能受到影响。

相关文章
  • C++ 中愚蠢的智能指针 2025-03-17
  • (评论) 2025-03-17
  • (评论) 2025-03-14
  • (评论) 2024-09-02
  • 防止每个 C 程序内存泄漏 2024-01-22

  • 原文
    Hacker News new | past | comments | ask | show | jobs | submit login
    Stupid Smart Pointers in C (kevinalbs.com)
    8 points by seansh 1 hour ago | hide | past | favorite | 4 comments










    Really, don't do this, it's a portability and safety nightmare (aside from C not being memory safe already).

    C programmers are better off with either of these two techniques:

    * Use __attribute__((cleanup)). It's available in GCC and Clang, and we hope will be added to the C spec one day. This is widely used by open source software, eg. in systemd.

    * Use a pool allocator like Samba's talloc (https://talloc.samba.org/talloc/doc/html/libtalloc__tutorial...) or Apache's APR.

    (I didn't include using reference counting, since although that is also widely used, I've seen it cause so many bugs, plus it interacts badly with how modern CPUs work.)



    Note that this will probably cause branch prediction misses, just like thread switching does - modern CPUs have a return address predictor which is just a simple stack. I don’t think you can avoid this without compiler support.


    I wonder how that affects compiler optimization


    and stack protection cookies






    Join us for AI Startup School this June 16-17 in San Francisco!


    Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact



    Search:
    联系我们 contact @ memedata.com