Prakash
Prakash

Reputation: 752

AccessViolation error while using _tcstok in C++

I am trying to run the following code

TCHAR* str1 = TEXT("C:\\Program Files\\Internet Explorer;");     
const TCHAR* del = TEXT(";");        
TCHAR* token = _tcstok(str1, del);   

When I run this in VS 2010 I get the following Exception :
Unhandled exception at 0x10275af4 (msvcr100d.dll) in String_Tchars.exe: 0xC0000005: Access violation writing location 0x0041839c.

My Objecttive to to be able to get the part before the semi-colon ";" and then do an append to that token to get the final string as c:\Program Files\Internet Explorer\iexplore.exe

Could someone shed some light what is causing this exception?

Upvotes: 0

Views: 381

Answers (2)

Alok Save
Alok Save

Reputation: 206566

_tcstok tries to modify the constant string(string Literal) causing an Undefined Behavior, which presents itself in the form of an access violation.

The string Literal I refer to here is:

TCHAR* str1 = TEXT("C:\\Program Files\\Internet Explorer;"); 
       ^^^^

The program should not modify it, and _tcstok tries to do that hence the Undefined Behavior.

Instead use modifyable non const string array:

TCHAR str1[] = TEXT("C:\\Program Files\\Internet Explorer;");

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477368

You can only use strtok() (and its Windows relatives) with modifiable strings. So make your strings local character arrays:

TCHAR str1[] = TEXT("C:\\Program Files\\Internet Explorer;");
TCHAR* token = _tcstok(str1, ";");
// etc.

The the tokenizer function actually modifies the string by replacing the delimiter by null bytes, so there's no way you can use this on a read-only string.

If your string comes to you through a pointer-to-const, copy it to a local array first (e.g. to a std::vector<TCHAR>):

void foo(const TCHAR * str)
{
  std::vector<TCHAR> s(str, _tcslen(str) + 1);  // local copy, includes null terminator
  TCHAR * str1 = s.data();  // or &s[0]
  TCHAR* token = _tcstok(str1, ";");
  // ...
}

Upvotes: 1

Related Questions