Should I free strtok() results?

Boyd Roberts boyd at necisa.ho.necisa.oz
Wed Apr 11 17:47:46 AEST 1990


In article <6501 at rouge.usl.edu> pcb at gator.cacs.usl.edu (Peter C. Bahrs) writes:
>The string [strtok] functions that return pointers to memory, should their
>results be freed?
>

No.  The string(3) functions that return pointers, return pointer values
to data that you have supplied as an argument.  Freeing their return
values will result in catastrophe.

More generally, never free returned memory that is static in nature.
Only free things that are explicitly malloced.  Read the manual.

Another thing to watch out for is a routine that has a partner that may
deallocate the object returned.  Eg:

    p = get_me_a_widgit();

    /* ... use *p */

    finished_with_widget(p);

The manual entry for the routine should be explicit enough to
state where it gets its storage from.  Most C library routines are fairly
simple and either use static data or operate on stuff passed as an argument.
The stuff you pass you should know when to free.



Boyd Roberts			boyd at necisa.ho.necisa.oz.au

``When the going gets wierd, the weird turn pro...''



More information about the Comp.lang.c mailing list