#Problem with strtok and malloc

13 messages · Page 1 of 1 (latest)

full prism
#

I do get the correct value with getNToken(), but when I try to free the memory it hangs.

char* getNToken(const char* str, const char* delim, const int pos)
{
    char* tmp = malloc(strlen(str)+1);
    strcpy(tmp,str);
    int pos_actual = 0;

    tmp = strtok(tmp,delim);
    while(pos_actual < pos)
    {
        tmp = strtok(NULL,delim);
        pos_actual++;
    }

    return tmp;
}

int main()
{
    char* d = getNToken("aaa,bbb,ccc",",",1);
    printf("%s\n",d);
    free(d);
    return 0;
}
brittle trellisBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

halcyon hatch
#

you need to give the pointer you got from malloc to free

#

i.e. it has to point to the start of the memory block

#

the tmp pointer you return will point to the middle of the memory block

full prism
#

so, doing free(d-(strlen(d)+1)) would be correct?

halcyon hatch
#

i would just return two pointers. one to the start of the memory block (so you can free it) and one to the token

#

for example you could add another parameter char **tofree which you set to the start of the memory block.

char *tmp = malloc(...);
*tofree = tmp;

// later in the main function
char *tofree;
char *d = getNToken(..., &tofree);
// the rest
free(tofree);
full prism
#

thx!

#

!solved

brittle trellisBOT
#

Thank you and let us know if you have any more questions!

#

[SOLVED] Problem with strtok and malloc

brittle trellisBOT
#

Problem with strtok and malloc