tags:

views:

42

answers:

3

I am trying the strtok in visual c++, but it seems not working. This not my first time using strtok, but i just counldnt figure out what is wrong with it. the code is quite simple.

in main

 cout<<getLevels("/'Group'/'Channel1'")<<endl;

in getLevels()

int getLevels(char * fullPath){
 int level=0;
 char *nextToken;
 char * pch=strtok_s(fullPath, "/", &nextToken);// broken at here
 while(pch!=NULL){
  level++;
  cout<<level<<":"<<pch<<endl;
  pch=strtok_s(NULL, "/",&nextToken);
 }
 return level;

}

it breaks at line

 char * pch=strtok_s(fullPath, "/", &nextToken);

with error:

Unhandled exception at 0x10273de8 (msvcr100d.dll) in tdmsTest.exe: 0xC0000005: Access violation writing location 0x0041c840.

and the cursor is pointing to this line in strtok_s.ini

 for ( ; *str != 0 ; str++ )
    {
        if (map[*str >> 3] & (1 << (*str & 7)))
        {
            *str++ = 0; // pointing here
            break;
        }
    }

i tried it in strtok() instead of strtok_s() before, but it has the same problem. can any one tell me what is wrong with my code?

+3  A: 

The strtok() function will modify it's argument. You're calling it on a string literal, which is typically in read-only storage.

unwind
+1  A: 

Strtok is trying to split the string by inserting nulls in place of the tokens. I'd guess that the literal "/'Group'/'Channel1'" is stored as a constant and can't be modified.

Try removing the "Enable String Pooling (/GF)" flag from the compiler options.

AShelly
thank you. you are right. after i change to char * temp=strdup("/'Group'/'Channel1'"); cout<<getLevels(temp)<<endl;it works.thanks
Grey
+1  A: 

The problem is that you're using stroke. Stop doing that!!! Strokes are bad for the mind. Use Boost.Tokenizer.

Noah Roberts
+1 for Tokenizer. I'd also suggest boost::algorithm::split.
Sam Miller