簡體   English   中英

二維char **數組中的strcpy()分段錯誤

[英]strcpy() segmentation fault in 2-dimensional char** array

我正在編寫一個shell來抓取輸入並將其存儲在字符串(char *)數組中。 要啟用像流水線操作這樣的UNIX操作,我希望能夠編寫像

echo this | function more | function2

為此,我在while循環中收集命令及其參數,並嘗試將參數數組的所有內容復制到一個新的二維數組中,該數組包含整個命令行,例如“ ls -f -a ”。 到目前為止,這是有效的,但是,然后,我試圖在命令行中找到“ | ”時重置循環,忽略“ | ”,並開始執行相同的新循環,直到'\\0'找到了,這標志着原始輸入的結束:

char* arguments[MAXARGS]; // holds argument components, e.g. "ls" or "-f"
char** arg_collection[MAXARGS][MAXARGS]; // supposed to hold command lines, e.g. "ls -f -a"
argc_current = 0; // iterator for the loop, counts arguments
col_iterator = 0; // iterator for amount of command lines
int sentinel = 1; // sentinel value for while loop
...

while(sentinel)
{
    arguments[argc_current] = (char*) malloc (sizeof(word)); // word is defined, just not listed on here - refers to the currently read command / argument
     strcpy(arguments[argc_current], word); // copy current word into arguments

    if(tokens[argc_current] == TOKEN_TERMINATOR || tokens[argc_curernt] == TOKEN_NULL)
    {
       sentinel = 0; // tokens holds information about the type of word, e.g. if it is '\0'
    }

    if(tokens[argc_current] == T_BAR) // if the word is "|"
    {
       for(i = 0; i < argc_current; i++)
       {
          strcpy(arg_collection[col_iterator][i], arguments[i]); // copy argument list into collection
       }

       col_iterator++; // increment command line counter
       argc_current = 0; // reset argument counter, restart the loop
    }

    else
    {
        arg_current++; // increment current argument counter
    }
}

evaluating arguments here..

第一個循環工作正常,例如,如果我鍵入

echo this | echo more |

它填充arg_collection[0][0]arg_collection[0][1] ,因此我得到“ echo this ”。 然而,在將col_iterator增加到1之后,在注意到第二個“|”時調用strcpy時,我以分段錯誤的形式撞到了一堵磚牆。 為什么?

它看起來像是一個word char* 如果是這樣,你應該改變

arguments[argc_current] = (char*) malloc (sizeof(word));

arguments[argc_current] = malloc(strlen(word)+1);

sizeof(word)將給出指針變量的大小,而不是它指向的數據的大小。 strlen告訴你word的字符數。 '\\0'終止符需要+1

首先,您應該在使用之前分配arg_collection。 (因為你沒有提供整個代碼,我假設你不這樣做)。

然后你在線上取消引用你的arg_collection兩次:

strcpy(arg_collection[col_iterator][i], arguments[i]); // copy argument list into collection

當你必須的時候

strcpy(arg_collection[col_iterator], arguments[i]); 

也就是說,當它只是一個char時,你將arg_collection中string col_iterator的索引i處的char視為char *。

暫無
暫無

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

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