2
votes

I'm working my way through a book on operating systems, and some of the book's sample code is giving me a runtime segmentation fault. I'm somewhat new to C from Java, and I'm hoping someone can point me in the right direction.

The little program here is supposed to generate a simple shell, read a command in and fork a process to execute it. The problem is in the book's code itself, at the "scanf" function call; when I input something at the "osh>" prompt, I get a segmentation fault.

Form what I know about C, I think memory might need to be allocated for the args array, but since it's an array declared directly in the main function, I think I might not need to. I figure that if I did, it would be in the book's code.

Anyway, here's the code that generates the fault:

char* args[MAX_LINE/2 + 1]; /* command line (of 80) has max of 40 arguments */

int should_run = 1; 

int i, upper;

while (should_run){   
    printf("osh>");
    fflush(stdout);


scanf("%s", args); /* THIS CAUSES SEGFAULT */

char* localArgs[3];
char* pch;

/* ... */

Thanks in advance for the help. Learning memory management in C is quite the journey.

2

2 Answers

3
votes

You are passing an array of pointers to scanf(), it expects an array of char.

An example of how to use scanf() correctly to scan a text string would be

char string[100];

if (scanf("%99s", string) == 1)
 {
    printf("scanned string: %s\n", string);
 }
else
 {
    printf("error: unexepected error in `scanf()'.\n);
 }

Read the link throughly to understand why I wrote this code like I did, if you do you will start to understand how scanf() works, and when you do you will start writing more robust programs, and probably stop using scanf() too.

3
votes
char* args[MAX_LINE/2 + 1];

This is creating an array of size (MAX_LINE/2+1) of char pointers. If you want to use one of these char pointers as string, you must allocate them:

args[which_arg] = malloc(arg_max_length*sizeof(char));

And to read a text into it:

scanf("%s", args[which_arg]);