簡體   English   中英

為什么一個段出現故障而另一個沒有?

[英]Why is one seg faulting and the other not?

嗨,我有一個程序需要將字符串數組與預定義的字符串進行比較,但是當我使用變量 args[0] 時,它在我的函數 strcmp 中工作,如下所示

int gash_execute(char **args){
    int i;

    if(args[0] == NULL){
        return 1;
    }

    for(i = 0; i < gash_command_num(); i++){
        if(strcmp(args[0], functions[i]) == 0){
            return(*function_address[i])(args);     
        } 
    }
    return gash_launch(args);
}

但是,當嘗試 strcmp args[i] 如下所示時,我遇到了段錯誤。 誰能幫我找到解決這個問題的方法?

int gash_execute(char **args){
    int i;

    if(args[0] == NULL){
        return 1;
    }

    for(i = 0; i < gash_command_num(); i++){
        if(strcmp(args[i], functions[i]) == 0){
            return(*function_address[i])(args);     
        } 
    }
    return gash_launch(args);
}

args[] 是一個以前用空格分隔的字符串數組,這個程序用於自定義 shell,所以假設在我的 shell 命令行中我輸入“cat echo ls” args[0] 將是“cat”等等。 但是現在我需要實現 i/o 重定向。 所以我需要檢查 args 的每個元素來檢查它們是否代表符號 "<" ">" "|" 如果其中之一是我們可以從那里拿走

沒有看到所有代碼,或來自valgrind等工具的報告,我不能肯定地說。 但是我可以告訴你,這個循環充滿了潛在的問題。

for(i = 0; i < gash_command_num(); i++){
    if(strcmp(args[i], functions[i]) == 0){
        return(*function_address[i])(args);     
    } 
}

它基於某個函數調用迭代三個數組( argsfunctionsfunction_address ),這些函數調用不將這些作為變量( gash_command_num() ),這些變量與這些數組中實際有多少元素具有未知關系。

它使用了兩個可以包含任何內容的全局變量( functionsfunction_addresses )。

如果所有這些事情都是相關的,我會建議明確說明......但我懷疑它們不是。 我懷疑你的循環邏輯是錯誤的。 它正在比較args[i]functions[i] 我懷疑gash_command_num()實際上是functions的大小,因此循環正在脫離args

我懷疑你真正想要做的是看是否args[0]在匹配任何函數名functions ,然后調用相關功能 如果args[0]ls那么您要檢查是否有ls的內置 shell 函數並使用所有參數調用它。

與其一遍又一遍地搜索列表,並且必須管理兩個並行列表,不如使用哈希表來提供更好的服務。 鍵是函數名,值是函數指針。 C 沒有內置的哈希表,但有很多庫。 Gnome Lib是 C 缺少的許多其他基本功能的可靠選擇。

使用哈希表並消除全局變量,您的代碼簡化為:

/* For encapsulation */
typedef int(*shell_function_t)(char **);

int gash_execute(char **args, GHashTable *shell_functions){
    int i;

    if(args[0] == NULL){
        return 1;
    }

    shell_function_t func = g_hash_table_lookup(shell_functions, args[0]);
    if( func ) {
        return(*func)(args);
    }
    else {
        return gash_launch(args);
    }
}

掃描管道現在是一個單獨的問題。 為此,您確實希望遍歷args查找特殊字符。 如果在創建args時確保它以空指針結尾,這args得更簡單。

for(int i = 0; args[i] != NULL; i++) {
    ...check if args[i] is special...
}

暫無
暫無

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

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