How is C managing memory in this situation?

77 views Asked by At

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?

2

There are 2 answers

2
0___________ On BEST ANSWER

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

0
Vlad from Moscow On

If you have a character array as for example:

char s[] = "Hello World";

then you can use a pointer that can point to any character of the array. For example this line:

char *p = s;   

that is equivalent to:

char *p = &s[0];   

points to the first character of the string "Hello World" stored in the array s.

This line:

p = s + 6;

sets the pointer p to point to the substring "World" of this string stored in the array s.

The function strtok splits the passed string to substrings substituting delimiters with zero characters '\0' and just returns a pointer to the selected word.

So for example in this statement:

pt = strtok(NULL, ":");

the function strtok just returns a pointer to the selected substring that is assigned to the pointer pt.

By analogy you can consider another function strchr that searches whether a specified character is present in a string and returns either the address of the first found such a character or NULL.

pt = strchr( line, ':' );