简体   繁体   中英

Trouble with making a shell in C

So I'm trying to make a shell script in c. It has to do the following: *exit on user input; quit *process a command with up to one argument

As a beginner in internal processes and process control, I'm having trouble and could use a point in the correct direction. For some reason, it only prints couldn't execute no matter what was inputted. Here's what I have now, am I missing something? or am I doing something incorrectly?

    int main(){
       int total_args;
       char *arg[3];
       pid_t cpid;
       char shell_prompt[] = "console:";
       char line[MAX_LINE];
       char command[MAX_LINE];
       char argument[MAX_LINE];

       while(!0){
           printf("%s", shell_prompt);
           fgets(line, MAX_LINE, stdin);
           total_args = sscanf(line, "%s %s", command, command_argument);
           arg[0] =  (char *) malloc(strlen(command));
         .....

   }

When you allocate storage for a string that you are going to copy you need to add an additional character for the '\\0' terminator, so:

           arg[1] = (char *) malloc(strlen(command_argument));

needs to be:

           arg[1] = malloc(strlen(command_argument) + 1);

otherwise the subsequent call to strcpy will write beyond the bounds of the allocated storage.

Note also that I have removed the redundant and potentially dangerous cast on the result of of malloc .

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