strtok and strtok_r

S

siddhu

Dear experts,

As I know strtok_r is re-entrant version of strtok.
strtok_r() is called with s1(lets say) as its first parameter.
Remaining tokens from s1 are obtained by calling strtok_r() with a
null pointer for the first parameter.
My confusion is that this behavior is same as strtok. So I assume
strtok_r must also be using any function static variable to keep the
information about s1. If this is the case then how strtok_r is re-
entrant?
Otherwise how it keeps the information about s1?

Regards,
Siddharth
 
J

jacob navia

siddhu said:
Dear experts,

As I know strtok_r is re-entrant version of strtok.
strtok_r() is called with s1(lets say) as its first parameter.
Remaining tokens from s1 are obtained by calling strtok_r() with a
null pointer for the first parameter.
My confusion is that this behavior is same as strtok. So I assume
strtok_r must also be using any function static variable to keep the
information about s1. If this is the case then how strtok_r is re-
entrant?
Otherwise how it keeps the information about s1?

Regards,
Siddharth

The reentrant version takes one more argument where it stores its progress:
http://www.bullfreeware.com/download/sources/aix43/libgtop-1.0.9.tar.gz/libgtop-1.0.9/support
// Skip GNU copyright
#include <string.h>
/* Parse S into tokens separated by characters in DELIM.
If S is NULL, the saved pointer in SAVE_PTR is used as
the next starting point. For example:
char s[] = "-abc-=-def";
char *sp;
x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
x = strtok_r(NULL, "=", &sp); // x = NULL
// s = "abc\0-def\0"
*/
char *strtok_r (char *s,
const char *delim,
char **save_ptr)
{
char *token;

if (s == NULL)
s = *save_ptr;

/* Scan leading delimiters. */
s += strspn (s, delim);
if (*s == '\0')
return NULL;

/* Find the end of the token. */
token = s;
s = strpbrk (token, delim);
if (s == NULL)
/* This token finishes the string. */
*save_ptr = strchr (token, '\0');
else
{
/* Terminate the token and make *SAVE_PTR point past it. */
*s = '\0';
*save_ptr = s + 1;
}
return token;
}
 
B

Ben Pfaff

siddhu said:
As I know strtok_r is re-entrant version of strtok.

This is true on a system compliant with, e.g., POSIX, but it is
not required by C. Followups set.
[...misunderstanding...]

I think the problem is that you do not realize that strtok_r
takes one more parameter than strtok, and uses that parameter to
save state from one call to the next.
 
C

Charlie Gordon

siddhu said:
Dear experts,

As I know strtok_r is re-entrant version of strtok.
strtok_r() is called with s1(lets say) as its first parameter.
Remaining tokens from s1 are obtained by calling strtok_r() with a
null pointer for the first parameter.
My confusion is that this behavior is same as strtok. So I assume
strtok_r must also be using any function static variable to keep the
information about s1. If this is the case then how strtok_r is re-
entrant?
Otherwise how it keeps the information about s1?

strtok_r takes an extra parameter, q pointer to a char * where it stores its
current state.

The implementation is quite straightforward:

char *strtok_r(char *str, const char *delim, char **nextp)
{
char *ret;

if (str == NULL)
str = *nextp;
str += strspn(str, delim);
if (*str == '\0')
return NULL;
ret = str;
str += strcspn(str, delim);
if (*str)
*str++ = '\0';
*nextp = str;
return ret;
}
 
C

CBFalconer

siddhu said:
As I know strtok_r is re-entrant version of strtok.
strtok_r() is called with s1(lets say) as its first parameter.
Remaining tokens from s1 are obtained by calling strtok_r() with
a null pointer for the first parameter. My confusion is that
this behavior is same as strtok. So I assume strtok_r must also
be using any function static variable to keep the information
about s1. If this is the case then how strtok_r is re- entrant?
Otherwise how it keeps the information about s1?

There is no such standard C function as strtok_r(). To discuss
such a function you have to give its source, in standard C.
However, I just happen to have a suitable replacement function
lying about, whose source follows:

/* ------- file tknsplit.c ----------*/
#include "tknsplit.h"

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
Revised 2006-06-13 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh) /* length tkn can receive */
/* not including final '\0' */
{
if (src) {
while (' ' == *src) src++;

while (*src && (tknchar != *src)) {
if (lgh) {
*tkn++ = *src;
--lgh;
}
src++;
}
if (*src && (tknchar == *src)) src++;
}
*tkn = '\0';
return src;
} /* tknsplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable tkn abbreviations */

/* ---------------- */

static void showtkn(int i, char *tok)
{
putchar(i + '1'); putchar(':');
puts(tok);
} /* showtkn */

/* ---------------- */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char tkn[ABRsize + 1];

puts(teststring);
t = s;
for (i = 0; i < 4; i++) {
t = tknsplit(t, ',', tkn, ABRsize);
showtkn(i, tkn);
}

puts("\nHow to detect 'no more tkns' while truncating");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ',', tkn, 3);
showtkn(i, tkn);
i++;
}

puts("\nUsing blanks as tkn delimiters");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ' ', tkn, ABRsize);
showtkn(i, tkn);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file tknsplit.c ----------*/

/* ------- file tknsplit.h ----------*/
#ifndef H_tknsplit_h
# define H_tknsplit_h

# ifdef __cplusplus
extern "C" {
# endif

#include <stddef.h>

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
revised 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh); /* length tkn can receive */
/* not including final '\0' */

# ifdef __cplusplus
}
# endif
#endif
/* ------- end file tknsplit.h ----------*/
 
C

Charlie Gordon

CBFalconer said:
There is no such standard C function as strtok_r(). To discuss
such a function you have to give its source, in standard C.
However, I just happen to have a suitable replacement function
lying about, whose source follows:

Come on, strtok_r is part of POSIX. Do you pretend POSIX is not popular
enough.
Multiple implementations of strtok_r have been posted before your answer.
/* ------- file tknsplit.c ----------*/
#include "tknsplit.h"

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The

Why skip blanks ? this is not strtok behaviour.
The code and the comment don't agree on what blanks are: by C99 Standard,
blanks are space and tab.
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

Your function definitely differs a lot from strtok that takes a collection
of delimiters instead of a single char.
The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

again, this is not the behaviour of strtok: sequences of separators are
considered one.
A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
Revised 2006-06-13 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh) /* length tkn can receive */
/* not including final '\0' */

I have reservations about your API:
- instead of returning a const char *, you should return the number of chars
skipped.
it would prevent const poisonning when you pass a regular char * but cannot
store the return value into the same variable... It would also allow
trivial testing of end of string.
- the lgh parameter should be the size of the destination array
(sizeof(buf)), out of consistency with other C library functions such as
snprintf, and to avoid off by one errors: if callers pass sizeof(destbuf) -
1, they wouln't invoke UB, whereas they would by passing sizeof(destbuf)
with your current semantics.
{
if (src) {
while (' ' == *src) src++;

while (*src && (tknchar != *src)) {
if (lgh) {
*tkn++ = *src;
--lgh;
}
src++;
}
if (*src && (tknchar == *src)) src++;
}
*tkn = '\0';
return src;
} /* tknsplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable tkn abbreviations */

/* ---------------- */

static void showtkn(int i, char *tok)
{
putchar(i + '1'); putchar(':');
puts(tok);
} /* showtkn */

/* ---------------- */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char tkn[ABRsize + 1];

puts(teststring);
t = s;
for (i = 0; i < 4; i++) {
t = tknsplit(t, ',', tkn, ABRsize);
showtkn(i, tkn);
}

puts("\nHow to detect 'no more tkns' while truncating");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ',', tkn, 3);
showtkn(i, tkn);
i++;
}

puts("\nUsing blanks as tkn delimiters");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ' ', tkn, ABRsize);
showtkn(i, tkn);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file tknsplit.c ----------*/

/* ------- file tknsplit.h ----------*/
#ifndef H_tknsplit_h
# define H_tknsplit_h

# ifdef __cplusplus
extern "C" {
# endif

#include <stddef.h>

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
revised 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh); /* length tkn can receive */
/* not including final '\0' */

# ifdef __cplusplus
}
# endif
#endif
/* ------- end file tknsplit.h ----------*/

Posting the source code to a public version strtok_r would have been more
helpful.
The only advantage your function offers over strtok_r is the fact that it
does not modify the source string.
 
M

Martien verbruggen

[snip]
There is no such standard C function as strtok_r(). To discuss
such a function you have to give its source, in standard C.
However, I just happen to have a suitable replacement function
lying about, whose source follows:

Come on, strtok_r is part of POSIX. Do you pretend POSIX is not popular
enough.

POSIX is very popular. So is cricket. Neither, however is topical here.

If there were no other place where POSIX were already discussed, one
would have been created, given its popularity.

POSIX is discussed on comp.unix.programmer, and the people there are
very knowledgeable about the subject.

Regards,
Martien
 
C

CBFalconer

Charlie said:
Come on, strtok_r is part of POSIX. Do you pretend POSIX is not
popular enough. Multiple implementations of strtok_r have been
posted before your answer.

Popularity doesn't enter into it. Presence in the standard library
does. strtok_r doesn't exist there. That makes it off-topic here
in c.l.c. (barring source).
Why skip blanks ? this is not strtok behaviour. The code and the
comment don't agree on what blanks are: by C99 Standard, blanks are
space and tab.

This is not strtok. It is tknsplit. This is behaviour that seems
more useful to me. You don't have to use it, but siddhu may wish
to.
.... snip ...

Posting the source code to a public version strtok_r would have
been more helpful. The only advantage your function offers over
strtok_r is the fact that it does not modify the source string.

Which, IMO, is a major improvement. It also detects missing
tokens. It (once more) is NOT strtok. I have no idea what
strtok_r is, except that it invades user namespace.
 
C

Charlie Gordon

Martien verbruggen said:
CBFalconer said:
siddhu wrote:

As I know strtok_r is re-entrant version of strtok.
[snip]
There is no such standard C function as strtok_r(). To discuss
such a function you have to give its source, in standard C.
However, I just happen to have a suitable replacement function
lying about, whose source follows:

Come on, strtok_r is part of POSIX. Do you pretend POSIX is not popular
enough.

POSIX is very popular. So is cricket. Neither, however is topical here.

If there were no other place where POSIX were already discussed, one
would have been created, given its popularity.

POSIX is discussed on comp.unix.programmer, and the people there are
very knowledgeable about the subject.

POSIX may not be topical here, but mentioning strtok_r as a widely available
_fixed_ version of broken strtok is more helpful to the OP than the useless
display of obtuse chauvinism expressed ad nauseam by some of the group's
regulars.

Why did C99 get published without including the reentrant alternatives to
strtok and similar functions is a mystery. I guess the national bodies were
too busy arguing about iso646.h. Other Posix utility functions are missing
for no reason: strdup for instance. Did the Posix guys patent those or is
WG14 allergic to unix ?
 
S

Sam Harris

Why did C99 get published without including the reentrant alternatives to
strtok and similar functions is a mystery. I guess the national bodies were
too busy arguing about iso646.h. Other Posix utility functions are missing
for no reason: strdup for instance. Did the Posix guys patent those or is
WG14 allergic to unix ?

You can easily write your own version of strdup in a couple lines. I use
the following:

char *strdup(char *s)
{
char *r=0;
int i=0;
do {
r=(char *) realloc(r,++i * sizeof(char));
} while(r[i-1]=s[i-1]);
return r;
}
 
C

Charlie Gordon

CBFalconer said:
Popularity doesn't enter into it. Presence in the standard library
does. strtok_r doesn't exist there. That makes it off-topic here
in c.l.c. (barring source).

I did post source code (my own, put in the public domain)
This is not strtok. It is tknsplit. This is behaviour that seems
more useful to me. You don't have to use it, but siddhu may wish
to.

You introduced your function like this: "I just happen to have a suitable
replacement function"
One would expect semantics to be a tad closer.
Which, IMO, is a major improvement. It also detects missing
tokens. It (once more) is NOT strtok. I have no idea what
strtok_r is, except that it invades user namespace.

You must be joking Mr Falconer. You probably never heard of Unix, or even
Linux... Or do you live on this remote planet Microsoft has not settled yet
? If you have no idea what strtok_r is, learn something new today:
http://linux.die.net/man/3/strtok_r or if you like Microsoft's version
better (part of the secure string proposal)
http://msdn2.microsoft.com/en-us/library/ftsafwz3(VS.80).aspx
 
C

Charlie Gordon

Sam Harris said:
Why did C99 get published without including the reentrant alternatives to
strtok and similar functions is a mystery. I guess the national bodies
were
too busy arguing about iso646.h. Other Posix utility functions are
missing
for no reason: strdup for instance. Did the Posix guys patent those or is
WG14 allergic to unix ?

You can easily write your own version of strdup in a couple lines. I use
the following:

char *strdup(char *s)
{
char *r=0;
int i=0;
do {
r=(char *) realloc(r,++i * sizeof(char));
} while(r[i-1]=s[i-1]);
return r;
}

This proves my point.

Adding useful functions like strdup would prevent newbies and jokers from
re-inventing them in the most cumbersome, inefficient, ugly error prone
ways.

Your function should take a const char *.
sizeof(char) is 1 by definition
Why do you cast the result of realloc ?
Your function invokes undefined behaviour when running out of memory, it
should return NULL instead.
 
R

Richard Heathfield

Charlie Gordon said:
"CBFalconer" <[email protected]> a écrit dans le message de (e-mail address removed)...


You must be joking Mr Falconer.

No, he's toeing the group line, such as it is. As far as comp.lang.c is
concerned, there is *no such function* as strtok_r. If this question
were to arise in, say, comp.unix.programmer, Chuck's answer might be
very different.
 
T

Tor Rustad

CBFalconer wrote:

[...]
I have no idea what
strtok_r is, except that it invades user namespace.

If you have no idea what those *_r functions are, it's time for you (as
a Linux user) to read Stevens APUE! :)


str[a-z] is reserved name space, so it isn't part of the user name space.
 
T

Tor Rustad

Richard said:
Charlie Gordon said:


No, he's toeing the group line, such as it is. As far as comp.lang.c is
concerned, there is *no such function* as strtok_r. If this question
were to arise in, say, comp.unix.programmer, Chuck's answer might be
very different.

I have seen Chuck post a number of times over in Linux forums, so it's
rather surprising if he doesn't know about POSIX.

Methinks he know, but choose here to pretend he doesn't! :)
 
J

jacob navia

Charlie said:
POSIX may not be topical here, but mentioning strtok_r as a widely available
_fixed_ version of broken strtok is more helpful to the OP than the useless
display of obtuse chauvinism expressed ad nauseam by some of the group's
regulars.

EXACTLY!

Why did C99 get published without including the reentrant alternatives to
strtok and similar functions is a mystery. I guess the national bodies were
too busy arguing about iso646.h. Other Posix utility functions are missing
for no reason: strdup for instance. Did the Posix guys patent those or is
WG14 allergic to unix ?

C99 did not change ANY of the bugs of the standard library

o non reentrant functions like strtok remained and no alternative
was proposed even if POSIX had developed one.

o Buffer overflows were written into the standard itself.
I had a lengthy discussion in comp.std.c about asctime()
and the fixed buffer of 26 position it says it needs. It
suffices to put some wrong values into the input structure
and you have a buffer overflow. But no corrective action
was taken. More, the commitee told the people reporting
the bug that it was OK to have a buffer overflow there.

o gets() was maintained of course. Only after lengthy discussions,
Mr Gwyn felt forced to propose a "fix" that would have fixed the
input buffer size to at least BUFSIZ. The committee apparently
decided that gets() was deprecated, maybe because of the discussion
in comp.std.c, I do not know. In any case it would have been
better to do it when C99 was published.

o Trigraphs were maintained in the standard.

And I could go on with those examples...
 
P

pete

Charlie said:
Sam Harris said:
On 15 Sep 2007 at 1:28, Charlie Gordon wrote:
You can easily write your own version
of strdup in a couple lines. I use
the following:

char *strdup(char *s)
{
char *r=0;
int i=0;
do {
r=(char *) realloc(r,++i * sizeof(char));
} while(r[i-1]=s[i-1]);
return r;
}

This proves my point.

Adding useful functions like strdup
would prevent newbies and jokers from
re-inventing them in the most cumbersome,
inefficient, ugly error prone ways.

Your function should take a const char *.
sizeof(char) is 1 by definition
Why do you cast the result of realloc ?
Your function invokes undefined behaviour
when running out of memory, it
should return NULL instead.

Intsead of using realloc in a loop,
I think most programmers would write strdup with
one function call to strlen and one to malloc and one to strcpy.
 
R

Richard Heathfield

pete said:

Intsead of using realloc in a loop,
I think most programmers would write strdup with
one function call to strlen and one to malloc and one to strcpy.

memcpy, surely? Why measure the string twice?
 
C

Charlie Gordon

Richard Heathfield said:
Charlie Gordon said:


No, he's toeing the group line, such as it is. As far as comp.lang.c is
concerned, there is *no such function* as strtok_r. If this question
were to arise in, say, comp.unix.programmer, Chuck's answer might be
very different.

If he would give a different answer on a different group, one of these
statements would be a lie or a joke.
So he is a fundamentalist, ostracist, extremist...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top