使用free()时出现无效指针错误

2024-04-27 08:14:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用C(在Linux(Ubuntu 14.04))编写一个Python扩展,遇到了动态内存分配的问题。我搜索了SO,发现free()调用上的几个帖子导致了类似的错误,因为free()试图释放未动态分配的内存。但我不知道下面的代码是否有问题:

#include <Python.h>
#include <stdio.h>
#include <stdlib.h>

static PyObject* tirepy_process_data(PyObject* self, PyObject *args)
{
    FILE* rawfile = NULL;
    char* rawfilename = (char *) malloc(128*sizeof(char));
    if(rawfilename == NULL)
         printf("malloc() failed.\n");
    memset(rawfilename, 0, 128);
    const int num_datapts = 0; /* Just  Some interger variable*/

    if (!PyArg_ParseTuple(args, "si", &rawfilename, &num_datapts)) {
          return NULL;
    }

    /* Here I am going top open the file, read the contents and close it again */

    printf("Raw file name is: %s \n", rawfilename);
    free(rawfilename);
    return Py_BuildValue("i", num_profiles);
}

输出为:

Raw file name is: \home\location_to_file\
*** Error in `/usr/bin/python': free(): invalid pointer: 0xb7514244 ***

Tags: thefreereturnifincludeargsnullnum
2条回答

请考虑“PyArg_ParseTuple”的API文档:https://docs.python.org/2/c-api/arg.html

不应将指针传递给已分配的内存,也不应在之后释放它。

根据documentation

These formats allow to access an object as a contiguous chunk of memory. You don’t have to provide raw storage for the returned unicode or bytes area. Also, you won’t have to release any memory yourself, except with the es, es#, et and et# formats.

(强调由我添加)

所以不需要首先使用malloc()分配内存。之后也不需要free()内存。

发生错误的原因是试图释放Python提供/分配的内存。所以C(malloc/free)无法释放它,因为C运行时不知道它。

相关问题 更多 >