防止每个 C 程序内存泄漏
Memory leak proof every C program

原始链接: https://flak.tedunangst.com/post/memory-leak-proof-every-C-program

C 程序中的内存泄漏问题可以使用“leakproof.c”中提供的简单解决方案来解决。 此代码提供了 malloc() 的另一种实现,称为 LeakSaver Malloc,它自动将每个分配的指针保存在名为 bigbucket 的大桶链表中。 通过这样做,所有先前分配的指针仍然可访问,并且在程序中的其他地方未引用时不会泄漏。 出于减少资源的目的,调用传统的 free 函数仍然是可选的,或者可以完全省略,从而导致内存使用模式不增加。 通过这些更改,可以消除每个 C 程序中的内存泄漏。 (字数:108字)

我没有偏好。 但关于讨论的主题,根据上一句的上下文: u+1f926 u+200d u+2640 u+fe0f:📚“问题解决了!” [表示笑声的表情符号、保全面子的手势、包含短语“问题解决了!”的语音气泡] [原文如此]
相关文章

原文

Memory leaks have plagued C programs for as long as the language has existed. Many solutions have been proposed, even going so far as to suggest we should rewrite C programs in other languages. But there’s a better way.

Presented here is a simple solution that will eliminate the memory leaks from every C program. Link this into your program, and memory leaks are a thing of the past.

leakproof.c
#include 
#include 

struct leaksaver {
        struct leaksaver *next;
        void *pointer;
} *bigbucket;

void *
malloc(size_t len)
{
        static void *(*nextmalloc)(size_t);
        nextmalloc = dlsym(RTLD_NEXT, "malloc");
        void *ptr = nextmalloc(len);
        if (ptr) {
                struct leaksaver *saver = nextmalloc(sizeof(*saver));
                saver->pointer = ptr;
                saver->next = bigbucket;
                bigbucket = saver;
        }
        return ptr;
}

Every allocated pointer is saved in the big bucket, where it remains accessible. Even if no other references to the pointer exist in the program, the pointer has not leaked.

It is now entirely optional to call free. If you don’t call free, memory usage will increase over time, but technically, it’s not a leak. As an optimization, you may choose to call free to reduce memory, but again, strictly optional.

Problem sovled!

Posted 19 Jan 2024 16:55 by tedu Updated: 19 Jan 2024 16:55
Tagged: c programming rants
联系我们 contact @ memedata.com