cpointersmemoryc-stringsstrtok

How is C managing memory in this situation?


Consider this implementation of strtok() in C

char *pt;
pt = strtok(line, ":");
if (pt != NULL)
{
    pt = strtok(NULL, ":");
}

why doesn't pt have to be explicitly allocated memory? Like pt[128] or pt = malloc(...)? I would have thought the above implementation would segfault. Do I have to worry about deallocation?


Solution

  • line has to reference modifiable char array and most strtok implementations are using this memory.

    It is the reason why you do not have to provide any additional memory for this operation.

    Remember that line will be modified (destroyed) during this operation.

    pt will hold (if not NULL) the reference to one of the elements of the array referenced by line