【问题标题】:Getting "pointer being freed was not allocated" error with using a go shared lib in python在 python 中使用 go 共享库时出现“未分配指针”错误
【发布时间】:2021-11-23 11:50:34
【问题描述】:

每当我在 pycharm 中运行共享库时,我都会不断收到此错误:

Python(20566,0x116d67dc0) malloc: *** error for object 0x5b6222f0: pointer being freed was not allocated
Python(20566,0x116d67dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

这是我的 go 代码变成了一个共享库:

package main

// #include <stdio.h>
// #include <stdlib.h>
// #include <errno.h>
import "C"


//export FreeCString
func FreeCString(ptr *C.char) {
    C.free(unsafe.Pointer(ptr))
}

//export TestString
func TestString() *C.char {
    return C.CString("Hello World")
}

这是我的 py 代码:

from ctypes import *
from ctypes import cdll

lib = cdll.LoadLibrary('./test.so')

b = lib.TestString()
lib.FreeCString(b)
print(b)

这里发生了什么?

【问题讨论】:

    标签: python-3.x go cgo


    【解决方案1】:

    一方面,您在释放它之后调用print(b),这显然是个坏主意。

    可能更重要的是,您从未告诉 Python lib.TestString返回类型,因此 Python 会做出假设。特别是:

    b = lib.TestString()
    

    由于您从未设置过lib.TestString.restype,Python 认为返回类型是普通的int。因此,b 设置为 32 位 int,这是因为丢弃了 64 位 c_void_p 的 64 位中的 32 位。 (要解决这个问题,set the restype to c_void_p。你应该为你调用的所有函数设置argtypes,尽管在你可能使用的机器上,这可能无关紧要。)

    lib.FreeCString(b)
    

    这会间接调用free((void *)(int)malloc(some_size))。由于指针值已被通过int 的通道损坏,free 调用随即失败,在您到达应存储在b 中的值的错误使用后停止程序之前.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2014-10-14
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      相关资源
      最近更新 更多