tags:

views:

263

answers:

4

I have this extremely strange behavior coming :

In the below code: If I comment the call to MyLogger then everything works fine that is I get the sTempNr tokenized and 4 tokens are printed . But if I uncomment the call to MyLogger for logging then only the iteration takes place once and in other testing class with similar code as below there is a looping taking place more than 4 times with redundant info being sent to MyLogger.

So, I checked with Purify tool to determine if there were some memory issues in MyLogger. Could not find any. MyLogger is using vaargs to extract args and vfprintf call to print.

I am not sure how to debug this code further. Any guidance would be appreciated!.

char sTempNr[41] = "1129Z13589.2.9.10";
char *sTempStr;
sTempStr = NULL;

sTempStr = strtok(sTempNr,".");
while (sTempStr)
{
     printf("in in TempStr[%s]\n",sTempStr);
      //MyLogger("write","","Temp String[%s]",sTempStr);

     sTempStr = strtok(NULL,".");
}
+1  A: 

Is the logger calling strtok?

Steven Sudit
+8  A: 

strtok() keeps some static data inside so probably MyLogger calls strtok(), either directly or indirectly.

Replace strtok() with strtok_r() (reentrant version of strtok()) to get around this problem.

qrdl
That's why I never, ever, use strtok(), and consider it to be the dumbest thing about C.
David Thornley
@David Like with any tool - if you use it carelessly you hurt yourself (or others), but it doesn't mean you should never use the tool.
qrdl
He's right. The problems with strtok() have nothing to do with "careless" users, and are limited entirely to bad library design.
Steve M
You should never use strtok.
MSN
Thanks that really worked!. Could you please share with me a list of C gotchas/things to take care so that I can avoid these mistakes?
techzen
@techzen There are many :) General rule - if you are going to use the function you have no prior experience with, carefully read man page for that function - man usually specifies what to be aware of.
qrdl
+1  A: 

Is MyLogger using strtok as well? Note that strtok is not stateless.

On Freund
A: 

Sounds like MyLogger is corrupting the string in sTempStr. Try printing it out again after the call to MyLogger. eg

 printf("in in TempStr[%s]\n",sTempStr);
 MyLogger("write","","Temp String[%s]",sTempStr);
 printf("in in TempStr[%s]\n",sTempStr);

and see if anything has changed

rikh
Even if it does, it doesn't matter as sTempStr is reassigned by next call to strtok().
qrdl