【问题标题】:Seg fault using strtok to parse stdin to an array使用 strtok 将标准输入解析为数组的段错误
【发布时间】:2014-09-08 16:01:46
【问题描述】:

每次代码到达第一个 strtok 时,我都会遇到段错误

token = strtok(commandLine," ");

我只是想解析标准输入并将其存储,使用空格作为分隔符。我看到的很多问题是人们在字符串文字上使用 strtok,我认为这也适用于我的情况,但是我该如何解决呢? 谢谢。

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

int main(int argc, char* argv[]){

    //Used for parsing
    char commandLine[255];
    char* tokens[10];
    char* token;
    int counter;
    int i;

    printf("gets to pt 1\n");
    //Parsing
    while( fgets(commandLine, 255, stdin) ){
        printf("\n%s\n", commandLine);
        token = strtok(commandLine," ");
        printf("gets here");
        counter = 0;
        for(counter = 0; token != NULL; counter++){
            strcpy(tokens[counter], token);
            token = strtok(NULL, " ");
        }   
    }
    printf("gets to point2");
    for(i = 0; tokens[i] != NULL; i++){
        printf("%s ", tokens[i]);
    }

编辑:

这是工作代码。

正如 User93353 指出的那样,我必须为我的令牌分配内存,所以我改变了

char* tokens[10] 

到

char tokens[10][100]

我的 for 循环没有正确结束,必须更改

tokens[i] != NULL

到

i<counter

-

int main(int argc, char* argv[]){

    //Used for parsing
    char commandLine[255];
    char tokens[10][100];
    char* token;
    int counter;
    int i;

    printf("gets to pt 1\n");
    //Parsing
    while( fgets(commandLine, 255, stdin) ){
        printf("\n%s\n", commandLine);
        token = strtok(commandLine," ");
        printf("gets here");
        for(counter = 0; token != NULL; counter++){
            strcpy(tokens[counter], token);
            token = strtok(NULL, " ");
        }
        printf("gets to printing");
        for(i = 0; i<counter; i++){
            printf("%s", tokens[i]);
        }
    }


}

【问题讨论】:

  • strcpy(tokens[counter], token); : tokens[counter] 不指向保留的内存。
  • 你必须为你的指针分配内存,即token = malloc(some_size);
  • strlen(tokens[i]) != 0 更改为 i &lt; counter。因为char tokens[10][100]; 未初始化。

标签: c stdin strtok


【解决方案1】:

为tokens 数组的每个元素分配内存。

简单的方法是将其声明为

#define SOME_SIZE 100

char tokens[10][SOME_SIZE];

否则,tokens[0]、tokens[1] 等会指向内存中的某个随机位置。 strcpy到那个随机位置会导致你的程序崩溃。

【讨论】:

  • 在我尝试将其输出到标准输出之前,它现在不会出现段错误。它会输出很多废话,直到最终给我一个段错误。我正在再次处理它,但我想我会添加这个。
  • 我通过将 for 循环从 do != NULL 更改为 strlen(text) != 0 来解决这个问题。
猜你喜欢
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 2011-05-01
相关资源
最近更新 更多