Python:ctypes + C malloc 错误。 C内存问题还是Python/ctypes问题?

标签 python c malloc ctypes

大家。我在使用 ctypes 和 C 代码时遇到内存分配错误。我想知道内存问题是否出在 C 内部,或者是由于 ctypes 使用不当引起的。内存错误是

python(79698) malloc: * error for object 0x15627ac08: incorrect checksum for freed object >- object was probably modified after being freed. * set a breakpoint in malloc_error_break to debug Abort

python(76110,0x7fff70062ca0) malloc: * error for object 0x7d807e1078907df: pointer being >freed was not allocated * set a breakpoint in malloc_error_break to debug Abort

取决于我如何编写下面代码的“free_some_memory”部分。我不会在这里发布一堆 C 代码,但假设我已经正确编写了 C 代码,我的 ctypes 接口(interface)看起来正确吗?

此外,对于给定版本的“free_some_memory”,我遇到的失败并不总是发生在脚本中的同一位置。 是否有可能我的 C 代码内存管理写得不好,以至于 Python 内存管理可能会也可能不会搞砸(取消)分配?

不知道这是否重要,但我正在使用 Mac Snow Leopard。
如果您能提供任何帮助,我们将不胜感激。

最好, jkmacc

我的 C 代码如下所示:

/**** cfunction.c ****/
int cfun (double *y, char datafile[1024], int byteoffset, int num )
{
  allocate_some_memory;
  do_stuff;

  if ( error_condition )
  {
    free_some_memory;
    return ( -1 );
  }

  fill_y_here;
  free_some_memory;
  return ( 0 );
}

我的 ctypes 包装器看起来像:

#pyfunction.py

import ctypes as C
import numpy as np

lib = C.CDLL('mylib.dylib')

def pyfun(DATAFILE, BYTEOFFSET, NUM):
    """
    DATAFILE: a string file name
    BYTEOFFSET: an integer
    NUM: an integer
    """

    #return integer success/failure flag
    lib.cfun.restype = C.c_int 

    #array memory to be filled inside of C
    Y = np.empty(NUM,dtype='double',order='C')

    cDATAFILE = C.create_string_buffer(DATAFILE,1024) 
    cBYTEOFFSET = C.c_int(int(BYTEOFFSET))
    cNUM = C.c_int(int(NUM))

    flag = lib.cfun(Y.ctypes.data_as(C.POINTER(C.c_double)), \ 
               cDATAFILE,cBYTEOFFSET,cNUM)

    if flag == -1:
        print("Something went wrong.")
        return -1
    else:
        return Y

最佳答案

我遇到了这个问题,这是我发现的:

如果您使用 ctypes 映射某些内容,然后释放它,则当 ctypes 对象被销毁时,您将收到错误消息。因此,在调用 free() 之前,您需要确保 python 代码中没有剩余的对它的引用。

所以,你的 C 代码将如下所示:

char* p;
char* allocate() {
 p = asprintf("hello world");
 return(p)
}
void freep() {
 free(p);
}

你的Python代码将是这样的:

allocate = clib.allocate
allocate.restype = c_char_p()
p = allocate()
print p
# This is the key:
del(p)
clib.freep()

如果你想看到错误,只需省略 del(p)

关于Python:ctypes + C malloc 错误。 C内存问题还是Python/ctypes问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6230719/

相关文章:

字符对齐奇怪的输出

c - 从 C 中的用户定义函数返回指针

c - 指向字符串数组的指针数组

Python:解决大文本文件的 "ValueError: too many values to unpack (expected 2)"问题?

python - 如何从 SymPy 分段对象中提取函数?

c - 函数原型(prototype)错误,应为 '=' ... 在 'int' 之前

c - C 中 malloc 分配的意外大小输出

python - psycopg2 错误 : DatabaseError: error with no message from the libpq

python - 对象列表 : Efficiently getting a list of sum of ith attribute

java - 与整数表示相比,浮点表示可以支持更大的值