指针崩溃无效

时间:2015-01-02 13:29:47

标签: python-3.x memory-management cython

我正在尝试使用Cython包装C库,并且尝试将字节对象传递给函数时出现失败。

我的Python如下:

def tou8(s):
    return s.encode('utf-8')

cdef char **alloc_strarr(in_arr, blen=0):
    size = len(in_arr)
    cdef char **out_arr = <char **>calloc(size, sizeof(char *))
    cdef char *tempb
    if out_arr is NULL:
        raise MemoryError()
    fail = 0
    for i in range(0, size):
        b = tou8(in_arr[i])
        if blen:
            out_arr[i] = <char *>calloc(blen, sizeof(char))
            if out_arr[i] is NULL:
                fail = i
                break
            tempb = b
            rc = snprintf(out_arr[i], blen, b'%s', tempb)
            if rc >= blen:
                fail = i
                break
        else:
            out_arr[i] = b
    if fail:
        for i in range(0, fail):
            free(out_arr[i])
        free(out_arr)
        raise MemoryError()
    return out_arr

# this function inside a larger cdef class
def __cinit__(self, fieldc, fieldnames, primkey=''):
    cdef char **cfields = alloc_strarr(fieldnames, blen=FMAXLEN)
    cprimkey = tou8(primkey)
    self._list = so.cq_new_dlist(fieldc, cfields, cprimkey)
    free_all(cfields, len(fieldnames))
    if self._list is NULL:
        raise Exception('Memory or value error creating DataList')

我尝试通过创建类的新实例来执行此操作。

$ python3
Python 3.4.2 (default, Dec 27 2014, 13:16:08) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymodule
>>> dl = mymodule.MyClass(1, ['test'])
*** Error in `python3': munmap_chunk(): invalid pointer: 0x00007fa4b6a17320 ***
Aborted

我的初始化过程出了什么问题?

1 个答案:

答案 0 :(得分:1)

当您编写out_arr[i] = b时,存储在out_arr[i]中的指针指向由b处理的内存,并且只有b指向的对象不是垃圾才有效收集(例如在下一次迭代期间)。