Reputation: 33
One of the two problems that the strtok_s
function (C11) solves is it prevents storing outside of the input string. As I understand it this would only be possible if you pass a non null terminated string to strtok
.
Is it correct that if I only ever pass properly null terminated strings to strtok
then there isn't a risk of it writing outside of the input string?
Upvotes: 2
Views: 231
Reputation: 7490
Let's start answering to the main question, about strtok
writing beyond the size of the buffer containing the string.
strtok
actually modifies the input string: it writes a string terminator ('\0'
) where the delimiter character used to be. In this way it can return to the user null-terminated tokens'\0'
is found in memory and write data if before the end is reached a delimiter is foundNow, we cannot say properly that "strtok_s
prevents storing outside of the input string" but we can say that this function provides a way to control the number of bytes of the input string that are examined, and as a consequence written (as explained above).
The control we are talking about is the same we have using strncpy
instead of strcpy
: we can pass to strtok_s
the maximum size if the input string avoiding memory corruption in case of missing string terminator.
Let's have a look to strtok_s()
signature:
char *strtok_s(char *restrict str, rsize_t *restrict strmax,
const char *restrict delim, char **restrict ptr);
Comparing it to strtok
's interface, we have two more parameters. The ptr
parameter is useful to make it reentrant and it is present also in strtok_r
. It is not directly related to this question.
The strmax
parameter is the one we are looking about
strmax - pointer to an object which initially holds the size of str: strtok_s stores the number of characters that remain to be examined
(the emphasis is mine).
So, passing to strmax
the pointer to a variable initialized with the size of the char buffer containing the input string, will make sure that a write beyond that size will ever occur.
Upvotes: 1