Creating my "mini shell" - Error: Segmentation Fault

2

I am developing a mini shell for a university practice and I run into an error that I have not been able to solve since according to what I have understood, searching in Google for my error, it is an error that can come out of several causes. Let's see if someone sees why I get the error. For a moment I thought it could be a misuse of the fgets [and I removed the line = fgets ... leaving only the fgets(.....); ] but it did not serve me what I thought would be a solution.

This is the error that the debugger gives me in the line of the

"line = fgets(line, MAX_LINE, stdin);"

Below I leave the code of the function that uses it with your explanation.

  

Program received signal SIGSEGV, Segmentation fault.   __GI__IO_getline_info (fp = fp @ entry = 0x7ffff7dd4640 < _IO_2_1_stdin_ & gt ;, buf = buf @ entry = 0x0, n = 510, delim = delim @ entry = 10,   extract_delim = extract_delim @ entry = 1, eof = eof @ entry = 0x0) at   iogetline.c: 86 86 iogetline.c: The file or directory does not exist.

#define PROMPT "$"                                              //declaramos el PROMPT que utilizaremos
#define MAX_LINE 512                                            //declaration of a variable that contains the max number of bits to read

/**
*read_line is a function that recibes a pointer as a parameter
*and returns the same pointer.
*This function prints the PROMPT,cleans the buffer and
*reads a line from the console.
*/
char *read_line (char *line) {
    printf("%s", PROMPT);
    if (fflush (stdout) != 0)
        printf ("the buffer hasn't been cleaned correctly");
    line = fgets(line, MAX_LINE, stdin);
    if (line == NULL)
        printf ("the line hasn't been read correctly or there was anything to read");
    return line;
}

int main() {
    char *line;
    while(read_line(line)) {
    execute_line(line);
    }
}
    
asked by Agustin Glenny 09.11.2016 в 14:50
source

1 answer

4

The fault is clear.

char *line;

You are stating a puntero that points to something, we do not know that.

Change it to

char line[MAX_LINE];

and everything should be fine.

In C, a code of type char NOMBRE[123] what it does is reserve memory for a group of 123 elements, each of which is a char ; they can be char or int or any other type.

A curiosity of the previous thing is that, to say it of some form, the previous expression returns a pointer; in fact, a char * and a char[] are interchangeable with each other. That is why you can keep calling your function read_line with the same argument, even if you have changed its type.

Changing the subject a bit, the Segmentation Fault that shows you, indicates that you tried to access the memory of your reach. Normally, remember that it does not belong to your process. In this case, when doing char *line; , the resulting pointer pointed to some unknown place , which would hardly be at your disposal.

    
answered by 09.11.2016 / 15:44
source