473,657 Members | 2,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strtok/strtok_r woes

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 believe that this is a pitfall into which many programmers may fall.
I have now changed the signature of my function to treat the input
string as a constant string, and I now making a local copy of the
string and operating on that. Of course, I now have to ensure that I
free up the dynamically allocated memory.
Ciao
KB

[I have posted my source listing to comp.sources.d]

Nov 14 '05 #1
23 3756
Modified source listing for my program using strtok_r in which I make a
local copy of the input string and operate strtok on that
// Program that parses strings of the form:
// Name, SS#, Emp#, Other#::Name, SS#, Emp#, Other#::Name, SS#, Emp#,
Other#
// and extracts the name and other attributes associated with an
employee
#include <stdio.h>
#include <iostream.h>
#include <fstream.h>

#include <list.h>

extern "C" char *strtok_r(char *s1, const char *s2, char **lasts);

#define MAX_DATA_LEN 128
#define EMPLOYEE_DELIMI TER_STR ":"
#define ATTR_DELIMITER_ STR ","
#define ATTR_DELIMITER_ CHAR ','
struct EmployeeInfo
{
char _name[MAX_DATA_LEN];
size_t _attributeCount ;
size_t *_attribute;

EmployeeInfo(co nst char *str):_attribut eCount(0), _attribute(NULL )
{
if(!strstr(str, ATTR_DELIMITER_ STR))
strcpy(_name, str);
else
{
char *temp1 = new char[strlen(str) + 1];
strcpy(temp1, str);
char *temp2 = temp1;

char* holdingBuf[1];

strcpy(_name, strtok_r(temp1, (const char *) ATTR_DELIMITER_ STR,
holdingBuf));
temp1 += (strlen(temp1) + 1);
_attributeCount = numChars(temp1, ATTR_DELIMITER_ CHAR) + 1;
_attribute = new size_t[_attributeCount];
memset(_attribu te, '\0', _attributeCount *sizeof(*_attri bute));

char* stringWithToken s = temp1;
char* token;
int i;
for(i =0;(token = strtok_r(string WithTokens, (const char *)
ATTR_DELIMITER_ STR, holdingBuf)) != NULL;
i++)
{
stringWithToken s = NULL;
_attribute[i] = atoi(token);
}

_attributeCount = i;

delete [] temp2;
}
}

virtual ~EmployeeInfo()
{
if(_attributeCo unt) delete [] _attribute;
}

void toString()
{
cout << "\nEmployee Name: " << _name << endl;
for(size_t i = 0; i < _attributeCount ; i++)
cout << "Attribute " << i << ": " << _attribute[i] << endl;
}

protected:
static size_t numChars(const char* str, const char delimiter)
{
size_t retVal = 0;
char ch;
for(size_t i = 0; ch = str[i]; i++)
{
if(ch == delimiter)
retVal++;
}
return retVal;
}
};
void
parseNameString (const char* nameString)
{
char *temp1 = new char[strlen(nameStri ng) + 1];
strcpy(temp1, nameString);
char *temp2 = temp1;
char* holdingBuf[1];

list<EmployeeIn fo*> empInfoList;

char* stringWithToken s = temp1;
char* token;
while((token = strtok_r(string WithTokens, (const char *)
EMPLOYEE_DELIMI TER_STR, holdingBuf)) != NULL)
{
stringWithToken s = NULL;
EmployeeInfo *newInfo = new EmployeeInfo(to ken);
empInfoList.pus h_back(newInfo) ;
}

delete [] temp2;

list<EmployeeIn fo*>::iterator itor, endOfList=empIn foList.end();

for(itor = empInfoList.beg in(); itor != endOfList; itor++)
{
EmployeeInfo* thisInfo = *itor;
thisInfo->toString();
}

for(itor = empInfoList.beg in(); itor != endOfList; itor++)
{

EmployeeInfo* thisInfo = *itor;
delete thisInfo;
}
}

int
main(int argc, char* argv[])
{
if(argc < 2)
{
cerr << "usage: " << argv[0] << " <inputfile>. Exiting ...." <<
endl;
exit(-1);
}

ifstream inFile(argv[1]);
if(!inFile)
{
cerr << "Error reading file " << argv[1] << " Exiting ...." <<
endl;
exit(-2);
}

char inputStr[MAX_DATA_LEN + 1];

/*
while(inFile >> inputStr)
{
cout << "** Parsing string " << inputStr << " **\n\n";
parseNameString (inputStr);
cout << "\n\n\n";
}
*/

while(inFile.ge tline(inputStr, MAX_DATA_LEN))
{
cout << "** Parsing string " << inputStr << " **\n\n";
parseNameString (inputStr);
cout << "\n\n\n";
}

exit(0);
}

Nov 14 '05 #2
The posting of the entire source listing to the comp.lang.c newsgroup
was an inadvertent mistake which is deeply regretted.

Nov 14 '05 #3
kb***@kaxy.com wrote:
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 believe that this is a pitfall into which many programmers may fall.
I have now changed the signature of my function to treat the input
string as a constant string, and I now making a local copy of the
string and operating on that. Of course, I now have to ensure that I
free up the dynamically allocated memory.
Ciao
KB

[I have posted my source listing to comp.sources.d]


char* strtok (char*, const char*);

strtok works by inserting '\0' in place of the delimiter each
successive call. Passing a string literal will definitely
cause trouble. Pass a string buffer. ;)

In fact, Herb-the-infamous-clown's book does what you did too!
Stay away from his books, unless you want an exercise
in debugging. ;)

Regards,
Jonathan.

--
"Women should come with documentation." - Dave
Nov 14 '05 #4
"Jonathan Burd" <jo***********@ REMOVEMEgmail.c om> wrote in message
news:35******** *****@individua l.net...

strtok works by inserting '\0' in place of the delimiter each
successive call. Passing a string literal will definitely
cause trouble. Pass a string buffer. ;)

In fact, Herb-the-infamous-clown's book does what you did too!
Wow, I knew he was spreading much misinformation, but
I didn't think it was *that* bad.

Stay away from his books, unless you want an exercise
in debugging. ;)


Too true.

-Mike
Nov 14 '05 #5
Mike Wahler wrote:
"Jonathan Burd" <jo***********@ REMOVEMEgmail.c om> wrote in message
news:35******** *****@individua l.net...
strtok works by inserting '\0' in place of the delimiter each
successive call. Passing a string literal will definitely
cause trouble. Pass a string buffer. ;)

In fact, Herb-the-infamous-clown's book does what you did too!

Wow, I knew he was spreading much misinformation, but
I didn't think it was *that* bad.

<snip>

I wonder if he even compiled the example he has given.
I've put large crosses in that book wherever I've discovered
such errors. (That's the only book that I've marked so far.
Heh.)

Regards,
Jonathan.

--
"Women should come with documentation." - Dave
Nov 14 '05 #6

"Jonathan Burd" <jo***********@ REMOVEMEgmail.c om> wrote in message
news:35******** *****@individua l.net...
Mike Wahler wrote:
"Jonathan Burd" <jo***********@ REMOVEMEgmail.c om> wrote in message
news:35******** *****@individua l.net...
strtok works by inserting '\0' in place of the delimiter each
successive call. Passing a string literal will definitely
cause trouble. Pass a string buffer. ;)

In fact, Herb-the-infamous-clown's book does what you did too!

Wow, I knew he was spreading much misinformation, but
I didn't think it was *that* bad.

<snip>

I wonder if he even compiled the example he has given.
I've put large crosses in that book wherever I've discovered
such errors. (That's the only book that I've marked so far.
Heh.)


Depending upon the implementation( s) used, compiling and
testing might not have caught it. Especially on older
systems I've used, I've seen them happily accept modifying
literals, and 'seem to work'. I think stuff like this
(depending upon behavior of particular implementation( s)
rather than the language rules for determining correctness)
could easily be the cause of many of the errors in his work.

-Mike
Nov 14 '05 #7
In the interest of "public disclosure" I am reproducing the coding
sample that I see in my copy of "C: The Complete Reference"

--NS

#include "stdio.h" /* NS: Shouldn't this be <stdio.h>? */
#include "string.h" /* NS: Shouldn't this be <string.h>? */

void main(void)
{
char *p;

p = strtok("The summer soldier, the sunshine patriot", " ");
/* NS: Passing a constant string to strtok */

printf(p); /* NS: Isn't %s missing here? */
do {
p = strtok('\0', ", ");
if(p) printf("|%s", p);
} while(p);
}

Nov 14 '05 #8
On 24 Jan 2005 18:37:09 -0800, ni************* @yahoo.com wrote in
comp.lang.c:
In the interest of "public disclosure" I am reproducing the coding
sample that I see in my copy of "C: The Complete Reference"

--NS

#include "stdio.h" /* NS: Shouldn't this be <stdio.h>? */
#include "string.h" /* NS: Shouldn't this be <string.h>? */
Yes, they both should. The #include "sometext" format is for
including source files, the #include <sometext> format is for
including standard headers, which need not be files.
void main(void)
This of course is just plain undefined behavior.
{
char *p;

p = strtok("The summer soldier, the sunshine patriot", " ");
/* NS: Passing a constant string to strtok */
No, your comment is in correct. He is passing the address of a string
literal, but the type of a string literal in C is "array of char" and
NOT "array of const char". Attempting to modify a string literal in C
does indeed produce undefined behavior, but not because the characters
are const, just because the C standard specifically says so.

Because attempting to modify a string literal is undefined, compilers
are free to actually make them const, but are not required to do so.
No strictly conforming program can tell one way or the other.
printf(p); /* NS: Isn't %s missing here? */
Not necessarily. If you pass a pointer to char to printf, assuming
that the pointer points to a valid string, printf will just output the
string. Unless of course the string happens to contain a conversion
specifier. If p points to "%s" for example, yet another incident of
undefined behavior occurs.
do {
p = strtok('\0', ", ");
if(p) printf("|%s", p);
} while(p);
}


Let it never be said that Schildt lacks the talent to cram multiple
examples of undefined behavior in such a small piece of code.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #9
ni************* @yahoo.com wrote:
In the interest of "public disclosure" I am reproducing the coding
sample that I see in my copy of "C: The Complete Reference"

--NS

#include "stdio.h" /* NS: Shouldn't this be <stdio.h>? */
#include "string.h" /* NS: Shouldn't this be <string.h>? */

void main(void)
{
char *p;

p = strtok("The summer soldier, the sunshine patriot", " ");
/* NS: Passing a constant string to strtok */

printf(p); /* NS: Isn't %s missing here? */
No.

I prefer using puts() for testing certain string functions
instead of printf() though. Take, for example, a function
that generates a string consisting of printable characters when you
specify a range, say "^A-Z" (all printable characters except those in
the range A-Z; ^ negates), the string will contain '%' and if you use
printf to test such a routine, it will result in UB. It is
easy to forget that your string may contain '%', so when
testing string functions, generally avoid using printf() unless
you really need it and know what you are doing.
do {
p = strtok('\0', ", ");
if(p) printf("|%s", p);
} while(p);
}


Another error is his incorrect usage of feof().

See his usage in his book and then read this:
http://www.drpaulcarter.com/cs/common-c-errors.php#4.2

Regards,
Jonathan.

--
"Women should come with documentation." - Dave
Nov 14 '05 #10

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

Similar topics

13
4916
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
3484
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
2725
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){
75
25092
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
17168
by: magicman | last post by:
can anyone point me out to its implementation in C before I roll my own. thx
0
8403
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8316
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
8737
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
8509
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
8610
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
4168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2735
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
1967
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1730
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.