简体   繁体   中英

seg fault during printf on variable I just set

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;
}

You're passing the pointer matched_command by value. Therefore it isn't changed by the call to is_command_built_in . So it retains it's uninitialized value.

Try this:

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;
}

command_to_run is uninitialized. The call to is_command_built_in could as easily have crashed. Such is the nature of undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM