Mark
Mark

Reputation: 81

Segmentation Fault in fgets()

I'm getting a segfault on fgets.
I tested using printf before and after and there is where it stops (in main method before while loop).
The ironic part is that I have another program that does the same call and it works.
Here is my code:

child(char * input){
    shrink(input);

    char ** words;
    char * word = strsep(&input, " ");
    int spaces = 0;

    while (word != NULL){
        words = realloc(words, ++spaces);

        if (words == NULL){ /* memory allocation failed */
            exit (1);
        }

        words[spaces-1] = word;
     word = strsep(&input, " ");
    }

    words = realloc (words, ++spaces);
    words[spaces] = NULL;

    char str[105];
    strcpy(str, "/bin/");
    strcat(str, words[1]);
    shrink(str);
    execvp(str, words);
    exit(0);

}

main() {

    char * input;
    int pid;

    printf("$ ");
    fgets(input, 100, stdin);

    while (strncmp(input, "exit", 4)){  /* while exit command has not been entered */
        pid = fork();
        if(pid == 0){           /* child process */
            child(input);
        }
        else if(pid < 0){       /* error while doing fork */
            exit(1);
        }
        else{                   /* parent process */
            wait(0);
        }

        printf("$ ");
        fgets(input, 100, stdin);
    }

    exit(0);

}

(The shrink method takes out \n from input)

Upvotes: 0

Views: 771

Answers (1)

Toby
Toby

Reputation: 10144

You have not allocated any memory to input, i.e. it has not been initialised. The address it holds is random and most likely points to an area of memory that is not writable (e.g. such as NULL) which is why there is a segmentation fault.

Upvotes: 1

Related Questions