hi im doing string tokenization similarly to the example below. however, within the while loop, i will be changing letter ‘a’ to ‘hellow’ for example. im getting segmentation fault when trying to change pch before assigning to myVar[i]. how should i go about doing it?
map <int, char*> myVar;
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
int i = 0;
while (pch != NULL)
{
printf ("%s\n",pch);
//modify token value
stringstream strStream;
strStream << "hello_world";
char newStr[7] = {0};
memcpy(newStr, strStream, 7);
myVar[i] = (char*)newStr;
pch = strtok (NULL, " ,.-");
i++;
}
I see two bugs inside of your
whileloop:1) you are passing the
stringstreamitself, not the data it contains, tomemcpy(). You are relying on thestringstream::operator void*()conversion operator. You are not supposed to deference that pointer, as it does not point at actual data. It is merely a flag to indicate whether thestringstreamis valid or not. To pass thestringstreamdata tomemcpy(), you have to call itsstr()method first to get astd::stringcontaining the data, and then call itsc_str()method to pass that data tomemcpy().2) when you are inserting values into your
std::map, you are inserting a localchar[]variable each time. Thatchar[]goes out of scope immediately afterwards, leaving thestd::mapcontaining pointers to random locations on the stack. Given the code you have shown, thechar[]buffers are likely to reuse the same stack space each time.Since you are using C++, you really should be using more C++-oriented things, like
std::string,std::cout, etc.Try this: