Question

I have the following method

void set_actions(char *input, char **actions)
{
   int index = 0;
   char *str = (char*)malloc(strlen(input));
   strcpy(str,input);
   char *tok = NULL;
   tok = strtok(str," ");

   while(tok!=NULL)
   {
     actions[index]=tok;
     tok=strtok(NULL," ");
     index++;
   }

   free(str);
}

after calling this method in main like:

char *input ="A B C";
char *actions[3];
set_actions(input, actions);

The result is:

actions[0] = is empty
actions[1] = is empty
actions[2] = C

if I delete the "free(str)" then

actions[0] = A
actions[1] = B

What am I doing wrong?

Was it helpful?

Solution 2

use

actions[index]=strdup(tok);

instead of

actions[index]=tok;

In fact tok is a pointer pointing to an address into the array str. When you free str, the tok become pointed to an address address that already freed. So you have to keep a copy of the tok content in another memory address. strdup allow to allocate memory and then copy the tok content in this memory

and then when your action[] array become useless in your code do not forget to free each elemet in the array

for (i=0;i<max;i++)
    free(actions[i]);

OTHER TIPS

strtok modifies the string in place. So the substrings that it returns are in fact segments of the buffer that you allocated for str, they are not in separate memory regions.

In C, a string runs until the next null byte (byte value 0). The way strtok works is that it replaces the string separator character by a null byte in place. So where you have before

+-----+-----+-----+-----+-----+-----+
| 'A' | '␣' | 'B' | '␣' | 'C' |  0  |
+-----+-----+-----+-----+-----+-----+
^
str

(where '␣' is a space character), then after calling strtok, you have

+-----+-----+-----+-----+-----+-----+
| 'A' |  0  | 'B' |  0  | 'C' |  0  |
+-----+-----+-----+-----+-----+-----+
^           ^           ^
actions[0]  actions[1]  actions[2]
str

You can't free str as long as you're using the tokens. Either make a copy of the tokens, or keep str around.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top