为什么使用strtok()会导致分段错误?

时间:2013-05-02 20:27:43

标签: c++ segmentation-fault strtok

我正在尝试使用strtok()在字符串中获取所有标记并将它们转换为整数。在获得一个令牌之后,尝试立即拉出另一个段错误 - 如何告诉系统这不是段错误条件以便它可以完成?

代码:

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

抛弃const为什么会出现段错误?如果是这样,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

抛开const讨论,这可能是你真正的问题;

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

答案 1 :(得分:1)

我认为应该是

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

因为它会分配新的空间。

但是,

char * charstarline = const_cast<char*>(line.c_str());,不会分配新的空间。

我通过执行以下示例得出了这个结论。

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