-1

Do you have to reallocate memory for a string every time you use strtok(), or does the function do this for you? I'm wondering, because I'm writing a program that reads a line from a file and breaks it into tokens. I want to store each token in a variable called cell. I could create multiple strings and put them in a linked list, but that would add a lot of overhead to the program, so I want to try to avoid it if I can. So say you set cell's value to the first string returned from strtok(), use it, and then set its value to the second string returned form strtok(), using an assignment statement. I understand that this would simply redirect the pointer to the new character array, abandoning the old array. Would this result in the old string becoming a lost object, or does strtok() free the old string for you?

user628544
  • 227
  • 3
  • 9
  • https://www.google.com/search?q=parse+a+string+using+strtok – alk Oct 26 '16 at 13:55
  • [`strtok`](http://en.cppreference.com/w/c/string/byte/strtok) does not allocate any memory. What makes you think it does ? – Jabberwocky Oct 26 '16 at 13:55
  • `strtok` successively replaces the delimiter by `'\0'`, which mutates the string but keeps the substrings inside of the original place in memory. – John Coleman Oct 26 '16 at 13:55
  • [Read this](http://xyproblem.info/) and [this](http://stackoverflow.com/help/how-to-ask). – Jabberwocky Oct 26 '16 at 13:56
  • 1
    Possible duplicate of [How does strtok() split the string into tokens in C?](http://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c) – John Coleman Oct 26 '16 at 13:58

2 Answers2

1

strtok does not allocate any strings, it inserts \0 characters into the source string and returns pointers that point to the now separated tokens. The memory for the source string is now memory that stores multiple strings (the tokens).

alain
  • 11,939
  • 2
  • 31
  • 51
0

strtok does not allocate any memory; it makes modifications to the string you pass in the initial call. The tokens are left in the original string being tokenized, so as long as that isn't deallocated (by you; strtok won't do it), your tokens will still be there.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101