C Wrapper Function, crashing Python?

Bernhard Herzog bh at intevation.de
Wed Oct 12 12:50:05 EDT 2005


"Java and Swing" <codecraig at gmail.com> writes:

> 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.

Looks fine.  I hope someValue does not point somewhere into the tmp
buffer, though.

> I also have things like...
>
> char *bar(char *in) {
>     char *results, *finalResults;
>     results = (char *) malloc(...);
>     finalResults = results;
>
>     while (...) { *results++ = some_val; }
>
>     return finalResults;
> }

Seems OK, too, assuming the results buffer is big enough.

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Skencil                                           http://skencil.org/
Thuban                                  http://thuban.intevation.org/



More information about the Python-list mailing list