473,805 Members | 2,030 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strtok and strtok_r

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

Sep 14 '07
75 25148
"Richard Heathfield" <rj*@see.sig.in valida écrit dans le message de news:
tJ************* *************** **@bt.com...
Charlie Gordon said:
>"Richard Heathfield" <rj*@see.sig.in valida écrit dans le message de
news: Ma************* ********@bt.com...
>>Charlie Gordon said:

"CBFalcone r" <cb********@yah oo.coma écrit dans le message de news:
46************* **@yahoo.com...

<snip>

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

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.progr ammer, 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.

...or a way of making a point, a la "Ich bin ein Berliner", with which
John F Kennedy bolstered the morale of West Berlin's citizens in June
1963. It was not "true" in the literal sense, but neither was it a lie
or a joke.
Except CBFalconer is no John F. Kennedy ;-)
His blunt rethoric does not bolster any one's morale, sarcasm does no good.
>So he is a fundamentalist, ostracist, extremist...

If you feel forced to resort to personal attacks, I can only assume you
have no logical arguments to put forward.
You are right, I should not have attributed to malice that which can be
adequately explained by plain ignorance. But I repeat: to not use strtok
anymore, check for availability of strtok_r or implement it locally from the
public domain source that has been posted above.

--
Chqrlie.
Sep 15 '07 #21
On Sep 15, 1:40 pm, "Joachim Schmitz" <nospam.j...@sc hmitz-digital.de>
wrote:
It s is NULL, this version only returns NULL if the implemenation's
malloc(0) returns NULL too
Entirely consistent with the standard library string functions - if
you pass them a char * that doesn't point to a string, the behavior is
undefined.

<OT>
And this is one case where "the thing you hope will happen" probably
doesn't - e.g. trying to compute strlen(NULL) on a GNU system produces
a seg fault).
</OT>
>
Bye, Jojo
Sep 15 '07 #22
"Joachim Schmitz" <no*********@sc hmitz-digital.dea écrit dans le message
de news: fc**********@on line.de...
"Joachim Schmitz" <no*********@sc hmitz-digital.deschri eb im Newsbeitrag
news:fc******** **@online.de...
>>
<Fr*********** *@googlemail.co mschrieb im Newsbeitrag
news:11******* *************** @g4g2000hsf.goo glegroups.com.. .
<snip>
My suggestion would be:

#include <stdlib.h>
#include <string.h>

char *my_strdup(cons t char *s)
{
size_t len;
char *t;
if(t=malloc(len =strlen(s)+1))
memcpy(t, s, len);
return t;
}

It s is NULL, this version only returns NULL if the implementation' s
malloc(0) returns NULL too
oops, sorry somehow my quoting was wrong.

Only the last sentence was mine...
And it does not make much sense ;-)
If s in NULL, strlen(s) invokes undefined behaviour.
otherwise, len is always0, and the code does not depend on the behaviour
of malloc(0)

--
Chqrlie.
Sep 15 '07 #23
<Fr************ @googlemail.com schrieb im Newsbeitrag
news:11******** *************@n 39g2000hsh.goog legroups.com...
On Sep 15, 1:40 pm, "Joachim Schmitz" <nospam.j...@sc hmitz-digital.de>
wrote:
>It s is NULL, this version only returns NULL if the implemenation's
malloc(0) returns NULL too

Entirely consistent with the standard library string functions - if
you pass them a char * that doesn't point to a string, the behavior is
undefined.
Fair enough, but I'd prefer my own functions to do better than that, so I
like Charlie Gordon's implementation better.
<OT>
And this is one case where "the thing you hope will happen" probably
doesn't - e.g. trying to compute strlen(NULL) on a GNU system produces
a seg fault).
</OT>
Damn, here too...
anwyway: see above

Bye, Jojo
Sep 15 '07 #24
<Fr************ @googlemail.com a écrit dans le message de news:
11************* ********@g4g200 0h...legrou ps.com...
On Sep 15, 2:02 pm, "Charlie Gordon" <n...@chqrlie.o rgwrote:
><Francine.Ne.. .@googlemail.co ma écrit dans le message de news:
1189858659.251 030.194...@g4g2 000hsf.googlegr oups.com...
>>My suggestion would be:

#include <stdlib.h>
#include <string.h>
>>char *my_strdup(cons t char *s)
{
size_t len;
char *t;
if(t=malloc(len =strlen(s)+1))
memcpy(t, s, len);
return t;
}

You code performs the task, but I find it misleading to call len a var
iable that is not the length of the string. I prefer to use size for
this purpose.

Furthermore, this code would not pass my default warning settings.
Assignment as an test expression is considered sloppy and error prone.

Tell that to Kernighan and Ritchie. :)
They might read this thread, I am sure they would care to comment.

Coding conventions is a very effective tool to catch bugs at an early
stage in development. Using all the help the compiler and other
automated tools can give at tracking potential errors disguised as
suspicious use of certain operators enhances productivity.

There is no gain at writing

size_t len;
char *t;
if(t=malloc(len =strlen(s)+1)) ...

instead of

size_t size = strlen(s) + 1;
char *t = malloc(size);
if (t) ...

The latter is much more readable and less error prone.

Your version did improve on mine by using memcpy to copy the '\0'
instead of writing separate code for that.

--
Chqrlie.
Is there a reason for the typo in your signature?
chqrlie is my handle, is there a reason you don't sign your messages ?
Sep 15 '07 #25
"Charlie Gordon" <ne**@chqrlie.o rgschrieb im Newsbeitrag
news:46******** *************** @news.free.fr.. .
<Fr************ @googlemail.com a écrit dans le message de news:
11************* ********@g4g200 0h...legrou ps.com...
>On Sep 15, 2:02 pm, "Charlie Gordon" <n...@chqrlie.o rgwrote:
>><Francine.Ne. ..@googlemail.c oma écrit dans le message de news:
1189858659.25 1030.194...@g4g 2000hsf.googleg roups.com...
My suggestion would be:

#include <stdlib.h>
#include <string.h>

char *my_strdup(cons t char *s)
{
size_t len;
char *t;
if(t=malloc(len =strlen(s)+1))
memcpy(t, s, len);
return t;
}

You code performs the task, but I find it misleading to call len a var
iable that is not the length of the string. I prefer to use size for
this purpose.

Furthermore , this code would not pass my default warning settings.
Assignment as an test expression is considered sloppy and error prone.

Tell that to Kernighan and Ritchie. :)

They might read this thread, I am sure they would care to comment.

Coding conventions is a very effective tool to catch bugs at an early
stage in development. Using all the help the compiler and other
automated tools can give at tracking potential errors disguised as
suspicious use of certain operators enhances productivity.

There is no gain at writing

size_t len;
char *t;
if(t=malloc(len =strlen(s)+1)) ...

instead of

size_t size = strlen(s) + 1;
char *t = malloc(size);
if (t) ...

The latter is much more readable and less error prone.

Your version did improve on mine by using memcpy to copy the '\0'
instead of writing separate code for that.
True but quite easy to fix:
char *my_strdup(cons t char *str) {
char *dest = NULL;

if (str) {
size_t size = strlen(str) + 1;
dest = malloc(size);
if (dest)
memcpy(dest, str, size);
}
return dest;
}
Sep 15 '07 #26
Charlie Gordon wrote:
"CBFalconer " <cb********@yah oo.coma écrit:
.... snip about tknsplit and strtok ...
>
>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/lib...z3(VS.80).aspx
This newsgroup is comp.lang.c. C is defined by the various C
standards, present or past, and includes K&R for times previous to
1989. None of these define, or even mention, strtok_r. Thus,
without standard C code, published in the same message, discussion
of it is off-topic here. The name is still reserved for the
implementor. As I said, it doesn't exist. Unix, Linux, Microsoft
have no influence whatsoever.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Sep 15 '07 #27
Richard Heathfield wrote:
CBFalconer said:

<snip>
>I have no idea what strtok_r is, except that it invades user
namespace.

No, it doesn't.
Well, it's not exactly a typo, but ....

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Sep 15 '07 #28
Charlie Gordon wrote:
"pete" <pf*****@mindsp ring.coma écrit:
.... snip ...
>>
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.

Or more efficiently calling memcpy instead of strcpy.

char *strdup(const char *str) {
size_t len;
char *dest = NULL;

if (str) {
len = strlen(str);
dest = malloc(len + 1);
if (dest) {
memcpy(dest, str, len);
dest[len] = '\0';
}
}
return dest;
}
I challenge the 'more efficient'. It will be highly dependent on
the compiler, but at the simplest you would be trading the effort
of an extra procedure call against the possible efficiency
improvement. Since most strings are short (in my case, probably
under 10 or 20 chars) this 'improvement' is a chimera. Also
bearing in mind that strdup is a system reserved name, my version
(with a #include <stdlib.h>) is:

char *dupstr(const char *str) {
char *dest, *temp;

if (dest = malloc(1 + strlen(str))) {
temp = dest;
while (*temp++ = *str++) continue;
}
return dest;
}

and I am willing to let it go boom when str is NULL, for early
warning etc. of problems.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Sep 15 '07 #29
Richard Heathfield wrote:
pete said:

<snip>
>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?
Huh? strcpy doesn't measure anything.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Sep 15 '07 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
3780
by: kbhat | last post by:
I had written some code using strtok_r for parsing strings with two "levels" of delimiters. The code was working like a charm, until it suddenly broke one day. You see, I was applying strtok on the input string itself, and as long as a variable string was passed to the function, everything was hunky dory. Then one day somebody decided to pass a constant string to my code ---- and everything came collapsing down like a domino. I...
6
476
by: gyan | last post by:
Hi How strtok track through string? char *strtok(char *s1, const char *s2); As i know The first call (with pointer s1 specified) returns a pointer to the first character of the first token, and will have written a null character into s1 immediately following the returned token. The function keeps track of its position in the string between separate calls, so that subsequent calls (which must be made with the first argument...
13
4931
by: ern | last post by:
I'm using strtok( ) to capture lines of input. After I call "splitCommand", I call strtok( ) again to get the next line. Strtok( ) returns NULL (but there is more in the file...). That didn't happen before 'splitCommands' entered the picture. The problem is in splitCommands( ) somehow modifying the pointer, but I HAVE to call that function. Is there a way to make a copy of it or something ? /* HERE IS MY CODE */ char *...
33
1022
by: Geometer | last post by:
Hello, and good whatever daytime is at your place.. please can somebody tell me, what the standard behavior of strtok shall be, if it encounters two or more consecutive delimiters like in (checks omitted) char tst = "this\nis\n\nan\nempty\n\n\nline"; ^^^^ ^^^^^^ char *tok = strtok(tst, "\n");
18
3498
by: Robbie Hatley | last post by:
A couple of days ago I dedecided to force myself to really learn exactly what "strtok" does, and how to use it. I figured I'd just look it up in some book and that would be that. I figured wrong! Firstly, Bjarne Stroustrup's "The C++ Programming Language" said: (nothing)
4
2737
by: Michael | last post by:
Hi, I have a proble I don't understand when using strtok(). It seems that if I make a call to strtok(), then make a call to another function that also makes use of strtok(), the original call is somehow confused or upset. I have the following code, which I am using to tokenise some input which is in th form x:y:1.2: int tokenize_input(Sale *sale, char *string){
14
3327
by: Mr John FO Evans | last post by:
I cam across an interesting limitation to the use of strtok. I have two strings on which I want strtok to operate. However since strtok has only one memory of the residual string I must complete one set of operations before starting on the second. This is inconvenient in the context of my program! So far the only solution I can see is to write a replacement for strtok to use on one of the strings. Can anyone offer an alternative?
3
441
by: siddhu | last post by:
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-...
11
17180
by: magicman | last post by:
can anyone point me out to its implementation in C before I roll my own. thx
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10609
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10360
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10366
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10105
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9185
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4323
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.