6

能防止大部分C程序内存泄漏的解决办法?

 7 months ago
source link: https://www.jdon.com/72017.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

能防止大部分C程序内存泄漏的解决办法? - 极道

自 C 语言存在以来,内存泄漏就一直困扰着该语言。人们提出了许多解决方案,甚至建议我们用其他语言重写 C 程序。但还有更好的方法。

这里介绍的是一个简单的解决方案,它将消除每个 C 程序的内存泄漏。将其链接到您的程序中,内存泄漏将成为过去。

include <dlfcn.h>
include <stdio.h>

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;
}

每个分配的指针都会保存在大桶中,并保持可访问状态。即使程序中不存在对指针的其他引用,指针也不会泄漏。

现在,调用 free 完全是可选的。如果不调用 free,内存使用量会随着时间的推移而增加,但从技术上讲,这并不是泄漏。

作为一种优化,你可以选择调用 free 来减少内存,但同样是完全可选的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK