c - strtok 导致段错误

标签 c string strtok

我必须获取字符串中的第三个单词并想使用strtok。现在,第一个 printf 可以工作,但之后我遇到了段错误。所以 tokenizedString = strtok(NULL, ""); 一定是导致问题的原因,对吧?

仅供引用:我正在查找字符串中的第三个单词,并且单词之间可以有尽可能多的空格。

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

char *tokenizeString(char *userCommand)
{
  char *tokenizedString;
  int counterForToken;
  tokenizedString = strtok(userCommand, " ");
  for(counterForToken = 0; counterForToken != 3; counterForToken++)
  {
    printf("%s\n", tokenizedString);
    tokenizedString = strtok(NULL, " ");
    if(tokenizedString == NULL)
    {
        break;
    }
  }
  printf("%s\n", tokenizedString);
  return tokenizedString; 
}

int main(void)
{
  char userCommand[255] = {0};
  fgets(userCommand, sizeof(userCommand), stdin);
  tokenizeString(userCommand);
}

最佳答案

Now, the first printf works but after that I get a Seg Fault. So tokenizedString = strtok(NULL, " "); must be causing the issue, right?

不,这是非常差的相关性。事实上,问题出在对 printf 的第二次调用中。当tokenizedString == NULL时,您可以传递它tokenizedString。指定的 %s 格式指定为期望指向以零结尾的字符数组的第一个字符的有效指针。传递它 NULL 是非法的,并且会导致未定义的行为(例如导致崩溃)。修复方法很简单:检查空指针值。当然,这同样适用于循环的第一次迭代

char *tokenizeString(char *userCommand)
{
  char *tokenizedString;
  int counterForToken;
  tokenizedString = strtok(userCommand, " ");
  for(counterForToken = 0; counterForToken != 3 && tokenizedString != NULL; counterForToken++)
  {
    printf("%s\n", tokenizedString);
    tokenizedString = strtok(NULL, " ");
  }
  if(tokenizedString != NULL)
    printf("%s\n", tokenizedString);
  return tokenizedString; 
}

关于c - strtok 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53902538/

相关文章:

c - 在 Keil 中使用 Arcom 的 C 嵌入式程序的目标和板

c - 堆栈粉碎检测到 C

c - 当我尝试将句子保存到 C 上的文本文件时出现错误

c - strtok 不返回任何值

c - 让 fgets 跳过特殊字符

c++ - 一个接受输入小写字母的短程序,它给出大写字母并在按下回车键时退出

ios - 在 Swift 中解析 JSON 后展开值

Java 获取字符串的子串

c++ - 在 C++ 中组合 char 和 Vector

c - 从 C 字符串中提取 POST 参数