C 示例:字符串驻留:去重、引用计数与指针相等
维护一张最多 16 项的驻留表:查找相同内容时直接复用已有指针并增加 refs,否则 malloc 一份副本登记。五次驻留 hello、world、hello、C、world 后,用指针比较验证相同字符串确实共享同一地址,最后统一释放。
🖥 在线运行GCC 10.2 · C11 标准 · 点 ▶ 运行 · 复制代码
🖨 参考输出与在线运行结果一致(标准 C11 环境)
malloc "hello" (refs=1, slot=0) malloc "world" (refs=1, slot=1) reuse "hello" (refs=2, slot=0) malloc "C" (refs=1, slot=2) reuse "world" (refs=2, slot=1) a==c: same pointer b==e: same pointer a==b: different pointers d starts with C: yes interned strings: 3
🧩 继续学习