简体   繁体   中英

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?

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;
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM