V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
guonaihong
V2EX  ›  程序员

golang 检测 cgo 内存泄露

  •  
  •   guonaihong ·
    guonaihong · 2019-10-21 09:35:33 +08:00 · 3973 次点击
    这是一个创建于 1647 天前的主题,其中的信息可能已经有所发展或是发生改变。

    此方法送给经常 cgo 的你,常在河边走(写 c 代码),哪有不湿鞋(内存泄露)。

    构造测试环境

    • cgo.go
    import (
        "fmt"
        "time"
        "unsafe"
    )
    
    func xx() {
        for i := 0; i < 100; i++ {
            p := C.my_malloc(200)
            fmt.Printf("%p\n", unsafe.Pointer(p))
        }   
    }
    
    func main() {
        time.Sleep(time.Second * 3)
    }
    
    

    bug.h

    
    #include "bug.h"
    #include <stdlib.h>
    void* my_malloc(size_t n) {
        return malloc(n);
    }
    
    

    bug.c

    
    #include "bug.h"
    #include <stdlib.h>
    void* my_malloc(size_t n) {
        return malloc(n);
    }
    
    

    运行

    gcc -shared bug.c -o libbug.so -g
    go build cgo.go
    LD_LIBRARY_PATH=. valgrind --leak-check=full --track-origins=yes ./cgo
    

    总结

    眼见的你已经发现熟悉的家伙,valgrind.valgrind 检测 c/c++代码可以,能在用在 go 的 cgo 环境吗? 亲测只能看到部分 c 的调用栈。还是要结合代码做分析。没有检测 c/c++代码来得爽,但比两眼一摸黑好多了。至少告诉你 cgo 的代码有没有内存泄露。

    交流学习

    有没有更好的在 cgo 检测内存泄露的方法???

    github

    https://github.com/guonaihong/gout

    2 条回复    2019-10-21 14:24:26 +08:00
    NoobPhper
        1
    NoobPhper  
       2019-10-21 13:30:50 +08:00 via Android
    1.14 新增了 arg 可以对 unsafe ptr 检测
    guonaihong
        2
    guonaihong  
    OP
       2019-10-21 14:24:26 +08:00
    @NoobPhper go1.14 版本?那还要等大半年。还挺期待的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2963 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 15:19 · PVG 23:19 · LAX 08:19 · JFK 11:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.