首页 > 解决方案 > 分段错误:使用 strtok,系统调用。C 编程

问题描述

我目前正在尝试两次 strtok 以标记文件传递的所有命令。第一轮标记化有效,但随后出现分段错误。可能是什么?我试图使所有数组更小,因为我认为这是一个内存问题。这也是用 C 编程的,我没有收到任何错误或警告。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>

int main(int argc, char *argv[])
{
        char content[100];
        int fd;
        ssize_t bytes = 0;
        fd = open(argv[1], O_RDONLY);
        int i = 0;

        char* token;
        const char a[2] = "\n";
        const char b[2] = " ";
        char storage[20][20];
        char temp[20][20];
        bytes = read(fd, content, sizeof(content)-1);
        close(fd);

        if(fd < 0)
        {
                write(1, "File doesn't exist\n", 19);
                return 1;
        }


        token = strtok(content, a);
        strcpy(storage[0],token);
        printf("%s\n",storage[0]);

        while(token != NULL)
        {
        i++;
        token = strtok(NULL, a);
        strcpy(storage[i],token);
        printf("%s\n",storage[i]);
        }

      token = strtok(storage[0],b);
        strcpy(temp[0], token);
        printf("%s\n",temp[0]);
        i = 0;

        while(token != NULL)
        {
        i++;
        token = strtok(NULL, b);
        strcpy(temp[i],token);
        printf("%s\n",temp[i]);

        }





return 0;

}

这是我得到的输出:

/bin/ls -l 
/bin/cat command.txt 
/usr/bin/wc -l -w command.txt 
??
Segmentation fault

标签: csegmentation-faultsystemsystem-callsstrtok

解决方案


    strcpy(storage[0],token);
    printf("%s\n",storage[0]);

您在 4 或 5 次中做同样的事情。您需要检查是否 token不为 NULL。否则你的程序只是UB

if( token)
{
    strcpy(storage[0],token);
    printf("%s\n",storage[0]);
}
else
{
    /* do something if token is NULL */
}

您还可以重新组织循环(以第一个循环为例):

    token = strtok(content, a);
    i = 0;

    while(token != NULL)
    {
    strcpy(storage[i],token);
    printf("%s\n",storage[i++]);
    token = strtok(NULL, a);
    }

推荐阅读