c - C的智能指针/安全内存管理?

标签 c memory pointers c99 smart-pointers

我和我认为许多其他人在使用智能指针来包装 C++ 中的不安全内存操作(使用 RAII 等)方面取得了巨大成功。但是,当您有析构函数、类、运算符重载等时,包装内存管理更容易实现。

对于使用原始 C99 编写的人,您可以指出哪里(不是双关语)来帮助安全内存管理?

谢谢。

最佳答案

这个问题有点老了,但我想我会花时间链接到我的 smart pointer library用于 GNU 编译器(GCC、Clang、ICC、MinGW、...)。

这个实现依赖于清理变量属性,一个 GNU 扩展,在超出范围时自动释放内存,因此,不是 ISO C99,而是带有 GNU 扩展的 C99。

例子:

simple1.c:

#include <stdio.h>
#include <csptr/smart_ptr.h>

int main(void) {
    smart int *some_int = unique_ptr(int, 1);

    printf("%p = %d\n", some_int, *some_int);

    // some_int is destroyed here
    return 0;
}

编译和 Valgrind session :

$ gcc -std=gnu99 -o simple1 simple1.c -lcsptr
$ valgrind ./simple1
==3407== Memcheck, a memory error detector
==3407== Copyright (C) 2002-2013, and GNU GPL\'d, by Julian Seward et al.
==3407== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==3407== Command: ./simple1 
==3407==
0x53db068 = 1
==3407==
==3407== HEAP SUMMARY:
==3407==     in use at exit: 0 bytes in 0 blocks
==3407==   total heap usage: 1 allocs, 1 frees, 48 bytes allocated
==3407==
==3407== All heap blocks were freed -- no leaks are possible
==3407==
==3407== For counts of detected and suppressed errors, rerun with: -v
==3407== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

关于c - C的智能指针/安全内存管理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799825/

相关文章:

c - 我需要在c中得到1000000的阶乘

c++ - Qt 错误地认为 QImage 被正确加载

c - C 中的指针和链表——程序的意外行为

C++双指针多态性

c++ - 将文件中的整数扫描到 C 中的数组中?

c - 使用 scanf 分隔冒号时出现问题

python - 查找内存使用情况、CPU 使用情况、运行 python 脚本的执行时间

c++ - 队列数组指针 (C++)

c - 如何在访问数组和二维数组时通过 c 中的 malloc 分配最大长度?

c - 为什么同一个指针有两个不同的内存地址? - C