Invalid pointer error when using free ()

I am writing a Python extension in C (on Linux (Ubuntu 14.04)) and have run into a problem with dynamic memory allocation. I searched for SO and found several messages about free () calls that caused similar errors because free () was trying to free memory that was not allocated dynamically. But I do not know if / how is the problem in the code below:

#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);
}

Conclusion:

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

According to the documentation :

. . , - , es, es #, et et #.

( )

malloc(). free() .

- , , ​​/ Python. , C (malloc/free) , C.

+4

, API `PyArg_ParseTuple ': https://docs.python.org/2/c-api/arg.html

.

+1

Source: https://habr.com/ru/post/1568012/


All Articles