gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:28:37 26 4
gpt4 key购买 nike

我和我认为许多其他人在使用智能指针来包装 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com