因此,当我在以下情况下调用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;
}
答案 0 :(得分:4)
您按值传递指针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;
}
答案 1 :(得分:2)
command_to_run
未初始化。对is_command_built_in
的调用可能很容易崩溃。这就是未定义行为的本质。