C Wrapper Function, crashing Python?

Java and Swing codecraig at gmail.com
Wed Oct 12 12:32:31 EDT 2005


As far as my C Wrapper functions are concerned...I no longer have the
need for free(...).  I do use PyMem_Free, for structures I allocated by
using PyMem_New(...).

In my C code I do have things such as...

char *foo(const char *in) {
    char *tmp;
    tmp = (char *) malloc((strlen(in) * sizeof(char)) + 1);
    strcpy(tmp, in);
    ...
    ...
    free(tmp);
    return someValue;
}

Is that appropriate?  I was under the impression that when you malloc
memory, you free it when done.

I also have things like...

char *bar(char *in) {
    char *results, *finalResults;
    results = (char *) malloc(...);
    finalResults = results;

    while (...) { *results++ = some_val; }

    return finalResults;
}

...is that correct?

As I mentioned earlier, when I run these functions from C I have no
troubles...I can run them 5, 10, 15 times, etc.  From Python, using my
wrapper function is when I have trouble.

Thanks in advance.

Bernhard Herzog wrote:
> "Java and Swing" <codecraig at gmail.com> writes:
>
> > thanks for the tip, however even when I do not free aString or bString,
> > i'm still crashing at the malloc in the c function, not the wrapper.
>
> Do you have any more places where you use free incorrectly?  In my
> experience, calling free with invalid values can corrupt the data
> structures used by the memory allocator in such a way that subsequent
> malloc calls crash.
>
>    Bernhard
>
> --
> Intevation GmbH                                 http://intevation.de/
> Skencil                                           http://skencil.org/
> Thuban                                  http://thuban.intevation.org/




More information about the Python-list mailing list