我正在尝试理解和学习 cgo,作为其中的一部分,我编写了一个使用C.stat.
import (
"fmt"
"unsafe"
"os"
)
//#include <sys/stat.h>
//#include <stdlib.h>
import "C"
func CheckPerm(filename string) {
statt := C.stat //stat struct from C
path := C.CString(filename)
st := *(*C.struct_stat)(unsafe.Pointer(statt)) //Casting unsafe pointer to C.struct_stat
defer C.free(unsafe.Pointer(path)) //free
defer C.free(unsafe.Pointer(statt))
C.stat(path, &st)
if st.st_mode & C.S_IRGRP > 0 || st.st_mode & C.S_IWGRP > 0 || st.st_mode & C.S_IXGRP > 0 || st.st_mode & C.S_IROTH > 0 || st.st_mode & C.S_IWOTH > 0 || st.st_mode & C.S_IXOTH > 0 {
fmt.Println("file permission too broad, make it non-readable to groups and others.")
os.Exit(1)
}
fmt.Println("File permission looks fine")
}
将文件路径传递给函数后,它会出错说
*** Error in `/tmp/Build go-sync.go and run77go': double free or corruption (out): 0x0000000000609480 ***
SIGABRT: abort
PC=0x7fe4302f3267 m=0
signal arrived during cgo execution
goroutine 1 [syscall, locked to thread]:
runtime.cgocall(0x401930, 0xc820097808, 0xc800000000)
/usr/lib/go/src/runtime/cgocall.go:120 +0x11b fp=0xc8200977d8 sp=0xc8200977a8
gosyncmodules._Cfunc_free(0x609480)
==========snip============
由于最后一行粘贴在这里gosyncmodules._Cfunc_free(0x609480),我删除了defer C.free(unsafe.Pointer(statt))它,现在它工作正常。
为什么当我尝试释放创建的结构时会抛出错误,而它可用于释放路径变量?
如果不是在这种情况下,类似的情况会导致内存泄漏吗?
阿波罗的战车
相关分类