ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] 参考:https://www.pengrl.com/p/29054/ ## Ubuntu下载valgrind ``` sudo apt-get install valgrind -y ``` ## Go代码示例 ``` // cstring.go package main /* #include <stdio.h> int c_print(const char* a) { //puts(a); } */ import "C" import ( "reflect" "unsafe" ) func getCString(s string) *C.char{ s = s + "\000" p := (*reflect.StringHeader)(unsafe.Pointer(&s)) return (*C.char)(unsafe.Pointer(p.Data)) } func main() { for i := 0; i < 99999 ; i++ { C.c_print(C.CString("hello world\n")) } } ``` 编译 ``` go build -o cstring cstring.go ``` ## 简单使用 ``` valgrind --leak-check=full ./cstring ``` 输入 ``` ==25893== LEAK SUMMARY: ==25893== definitely lost: 1,299,987 bytes in 99,999 blocks ==25893== indirectly lost: 0 bytes in 0 blocks ==25893== possibly lost: 1,440 bytes in 5 blocks ==25893== still reachable: 0 bytes in 0 blocks ==25893== suppressed: 0 bytes in 0 blocks ==25893== ==25893== For counts of detected and suppressed errors, rerun with: -v ==25893== Use --track-origins=yes to see where uninitialised values come from ==25893== ERROR SUMMARY: 9 errors from 7 contexts (suppressed: 0 from 0) ``` 可以看到,虽然valgrind给出了`definitely lost`的结果,但是几乎无法直接找到泄漏的位置。