Why does this use of strtok() cause segmentation fault?

I am trying to get ALL tokens in a string using strtok() and convert them to integers. After getting one token, trying to pull another promptly segfaults - how do I tell the system that this is not a segfault condition so it can complete?

Code:

char * token;
while ( getline (file,line) )
{
  char * charstarline = const_cast<char*>(line.c_str()); //cast to charstar
  char * token;
  token = strtok(charstarline," ");
        token = strtok(charstarline," ");
  int inttoken = atoi(token);
  cout << "Int token: " << inttoken << endl;
  while (token != NULL)
  {
token = strtok (NULL, " ");
int inttoken = atoi(token);
cout << "Int token (loop): " << inttoken << endl;
  }

Is casting away const why it segfaults? If so how do I get around this?

Answers


const discussion aside, this is probably your real problem;

while (token != NULL)                // Up to the last token, is not NULL
{
  token = strtok (NULL, " ");        // No more tokens makes it go NULL here
  int inttoken = atoi(token);        // and we use the NULL right away *boom*
                                     // before checking the pointer.
  cout << "Int token (loop): " << inttoken << endl;
}

I think it should be

char *  charstarline = malloc(sizeof(char)+1 * line.c_str() )  

Because it will allocate new space.

But,

char * charstarline = const_cast<char*>(line.c_str());, will not allocate new space.

I came to this conclusion, by executing the below example.

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;
int main(){

   char  charstarline[] = "hello abc def how\0"; //cast to charstar
   //here char * charstarline = "hello abc def how\0" is not working!!!!!

   char * token;
   token = strtok(charstarline," ");

   //int inttoken = atoi(token);
   //cout << "Int token: " << inttoken << endl;
   while (token != NULL)
   {
          token = strtok (NULL, " ");
          //int inttoken = atoi(token);
          cout << "Int token (loop): " << token << endl;
    }
 }

Need Your Help

Prompt box with 2 text fields

php javascript

I am trying to make a social website.I need to create a pop up window(may be prompt box in javascript) when the user clicks on create message button.The pop up window should contain 2 text fields j...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.