簡體   English   中英

分段錯誤:使用strtok,系統調用。 C程序設計

[英]Segmentation fault: Using strtok, system calls. C programming

我目前正在嘗試兩次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
  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);
    }

當您的程序嘗試訪問超出分配給您的程序的內存區域時,就會發生分段錯誤。 由於您僅分配了大小為20的數組用於存儲,並且存儲的數組數超過了該數,這是一個問題。 另外,您還分配了大小為20的數組,用於每行存儲令牌,這可能不足,具體取決於每行擁有的令牌數量。 除此之外,像其他提到的一樣,您還需要檢查strtok是否返回null。 嘗試取消引用空指針也會導致分段錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM