所以我在以下情況下調用printf時發生seg故障。我只是看不到我做錯了什麼。有任何想法嗎?太感謝了。我在代碼中標記了位置,在那裏我通過註釋(在第一部分代碼中)得到了seg錯誤。在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;
}
多數民衆贊成在我正在尋找。我知道我做錯了什麼。非常感謝你。 – james
就是我剛纔說的,它只是在is_command_built_in函數的範圍內初始化的,當它返回到主程序時,seg會發生故障,因爲它沒有在該範圍內初始化? – james
正確。在原始版本中,當您將它傳遞給函數時,它會將指針的副本放入本地作用域中。因此,當您分配給它時,它只會更改本地副本。當您最終退出該功能時,該本地副本將死亡。並且您將保留未初始化且無效的原始值。 – Mysticial