【问题标题】:seg fault during printf on variable I just set我刚刚设置的变量在 printf 期间出现段错误
【发布时间】:2011-09-29 04:26:54
【问题描述】:

所以当我在以下情况下调用 printf 时会出现段错误。我只是看不出我做错了什么。有任何想法吗?太感谢了。我已经在代码中用注释标记了我得到 seg 错误的位置(在第一块代码中)。

...
    char* command_to_run;
    if(is_command_built_in(exec_args, command_to_run)){
        //run built in command
        printf("command_to_run = %s\n", command_to_run); // <--- this is where the problem is
        run_built_in_command(exec_args);
    }
...

int is_command_built_in(char** args, char* matched_command){
    char* built_in_commands[] = {"something", "quit", "hey"};
    int size_of_commands_arr = 3;
    int i;
    //char* command_to_execute;
    for(i = 0; i < size_of_commands_arr; i++){
        int same = strcmp(args[0], built_in_commands[i]);
        if(same == 0){
            //they were the same
            matched_command = built_in_commands[i];
            return 1;
        }
    }
    return 0;
}

【问题讨论】:

    标签: c pointers segmentation-fault printf


    【解决方案1】:

    您正在按值传递指针matched_command。因此,调用is_command_built_in 不会改变它。所以它保留了它的未初始化值。

    试试这个:

    char* command_to_run;
    if(is_command_built_in(exec_args, &command_to_run)){   //  Changed this line.
        //run built in command
        printf("command_to_run = %s\n", command_to_run); // <--- this is where the problem is
        run_built_in_command(exec_args);
    }
    
    
    int is_command_built_in(char** args, char** matched_command){   //  Changed this line.
        char* built_in_commands[] = {"something", "quit", "hey"};
        int size_of_commands_arr = 3;
        int i;
        //char* command_to_execute;
        for(i = 0; i < size_of_commands_arr; i++){
            int same = strcmp(args[0], built_in_commands[i]);
            if(same == 0){
                //they were the same
                *matched_command = built_in_commands[i];   //  And changed this line.
                return 1;
            }
        }
        return 0;
    }
    

    【讨论】:

    • 这就是我想要的。我知道我做错了什么。非常感谢。
    • 是我最初所说的,它只是在 is_command_built_in 函数的范围内初始化,当它返回到主程序时,它出现了段错误,因为它没有在那个范围内初始化?
    • 正确。在原始版本中,当您将它传递给函数时,它会将指针复制到本地范围中。因此,当您分配给它时,它只会更改本地副本。当您最终退出该功能时,该本地副本就会消失。剩下的是未初始化且无效的原始值。
    • 这一切对我来说都是有意义的,但即使是现在,当我做出建议的更改时,我也会在“*matched_command = built_in_commands[i]”这一行上遇到一个段错误。我认为那里正在发生我不知道的其他事情
    • 您是否将char* matched_command 更改为char** matched_command?我忘了在我的答案中标记它。尽管如果您不进行更改,它不应该编译。
    【解决方案2】:

    command_to_run 未初始化。对is_command_built_in 的调用很容易崩溃。这就是未定义行为的本质。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-14
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多