printf 期间我刚刚设置的变量出现段错误
所以当我在以下情况下调用 printf 时,我会出现段错误。我只是看不出我做错了什么。有什么想法吗?谢谢一百万。我已经用注释标记了代码中出现段错误的位置(在代码的第一块中)。
...
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;
}
So I'm seg faulting when I call printf in the following situation. I just can't see what I'm doing wrong. Any ideas? Thanks a million. I've marked the spot in the code where i get the seg fault with a comment (in the first chunk of code).
...
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在按值传递指针
matched_command
。因此,调用is_command_built_in
不会改变它。所以它保留了未初始化的值。试试这个:
You're passing the pointer
matched_command
by value. Therefore it isn't changed by the call tois_command_built_in
. So it retains it's uninitialized value.Try this:
command_to_run
未初始化。对is_command_built_in
的调用很容易崩溃。这就是未定义行为的本质。command_to_run
is uninitialized. The call tois_command_built_in
could as easily have crashed. Such is the nature of undefined behavior.