簡體   English   中英

函數調用后strtok()崩潰的程序被多次調用

[英]strtok() crashing program after function calling it is called more than once

我在弄清楚為什么strtok()導致程序崩潰時遇到了一些麻煩

main()
{
    NodePtr root, cwd;
    char line[128] = {'\0'};
    char command[16] = {'\0'};
    char pathname[64] = {'\0'};
    char dirname[64] = {'\0'};
    char basename[64] = {'\0'};

    root = (NodePtr)malloc(sizeof(Node));

    gets(pathname);

    strcpy(root->name, "/");
    root->nodeType = 'D';
    root->childPtr = NULL;
    root->parentPtr = NULL;
    root->siblingPtr = NULL;

    mkdir(&root, pathname);
    mkdir(&root, "/abc/fa");
}

當我第一次調用mkdir時,一切都按預期工作(更具體地說,使用strtok())。 但是,一旦第二次調用mkdir,則在調用mkdir時我的程序崩潰。

    void mkdir(NodePtr *root, char pathname[64])
    {
        char dirname[64] = {'\0'}; //only local variable for dirname
        char basename[64] = {'\0'};  //only local variable for basename
        int i = 0;
        int j = 0;
        int cut = 0;
        int numOfDir = 0; //number of directories
        int len = 0;  //length of entered pathname
        char* tok; //temp value to tokenize string and put it into dirPath

        char** dirPath;  //an array of strings that keeps the pathway needed to take to create the new directory

        NodePtr newNode;
        NodePtr currNode;
        NodePtr currParentNode;

        tok = "\0";

        ........

        printf("tok: %s\n", tok);
        tok = strtok(pathname, "/");   //start first tokenized part
        strcpy(dirPath[i], tok);  //put first tokenized string into dirPathp[]
    //  printf("string: %s\n", dirPath[i]);
        i++;
        while(i < numOfDir)
        {
            tok = strtok(NULL, "/");
            strcpy(dirPath[i], tok); //put tokenized string into array dirPath[]
    //      printf("string: %s\n", dirPath[i]);
            i++;
        }
         ..........

我的程序專門在

tok = strtok(pathname, "/"); 

strtok是否保留了第一次調用mkdir的輸入,這就是為什么它崩潰了? 對於strtok來說還很陌生,因此感到抱歉。 謝謝!

您沒有使用strtok本身就是錯誤的,但使用的是 C字符串文字錯誤。

void mkdir(NodePtr *root, char pathname[64])

此函數原型等效於void mkdir(NodePtr *root, char *pathname) ,應以這種方式編寫。 我之所以提及這一點,是因為必須了解您是通過引用將字符串傳遞到mkdir ,這一點很重要。

mkdir(&root, pathname);
mkdir(&root, "/abc/fa");

在第一次調用時, pathname參數設置為指向mainpathname變量,該變量位於可寫內存中,因此一切正常。

在第二個調用中, pathname變量設置為指向字符串文字"/abc/fa" ,該字符串位於只讀內存中,因此會崩潰。 如果您在mkdir中執行任何嘗試通過庫函數或其他方式修改pathname指向的數組的操作,都會遇到相同的崩潰。

最簡單的解決方法是編寫

char pathname2[64] = "/abc/fa";

main ,然后傳遞mkdir ; 這將導致編譯器生成從字符串文字到另一個可寫字符數組的副本。 更復雜的方法是可行的,甚至是可取的,但是我必須對您的更大目標有更多的了解。

暫無
暫無

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

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