sworwitz
sworwitz

Reputation: 19

String bug in my_shell program

I'm trying to create a simple shell program which execute the program specified in input. There are two main function: scanner() (use strtok to split the input in token) and execute() (fork the process and execute the program).

Unfortunately it doesn't work... I've tried to print string[0] at the end of scanner() and at the beginning of execute(). The first time the output is correct but the second time string[] seems to be modified in a sequence of random numbers so execvp() doesn't work...

I really can't figure out why the values of string[] changes, probably is a very stupid error but I can't see it. I really need your help! Thanks in advice.

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

#define DIM 256

int scanner(char*[]);
int execute(char*[]);

int main()
{
    char* string[DIM]; 

    scanner(string);
    execute(string);

}

/* scan:    read the input in token*/
int scanner(char* string[])
{
    char input[1024];
    char delimit[]=" \t\r\n\v\f"; 
    int i = 0;

    if(fgets(input, sizeof input, stdin)) {
        string[i] = strtok(input, delimit);
        while(string[i]!=NULL){
            i++;
            string[i]=strtok(NULL,delimit);
        }
        return 0;
    }
    return 1;
}
/* execute:    execute the command*/
int execute(char* string[])
{
    int pid;
    printf("%s\n", string[0]);
    switch(pid = fork()){
        case -1:
            return 1;
        case 0:
            execvp(string[0], string);
            return 1;
        default:
            wait((int*)0);
            return 0;
    }
}

Upvotes: 1

Views: 93

Answers (1)

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27652

The string variable input in scanner is a local variable, with storage class "auto". That means that when that function returns, that variable disappears, and the memory it occupied can be re-used for other things. That is unfortunate, since strtok returns pointers into that string variable.

Upvotes: 3

Related Questions