Question

So I am building a shell and one command I am implementing is the prompt. This will take an argument and set that as the prompt, but if no argument is entered it will ask for user input and then use that..... that's worded very terribly so here's an example:

[SHELL] prompt code
code[SHELL] ls
code[SHELL] ....

or

[SHELL] prompt
please enter a prefix: (user input goes here, say code again)
code[SHELL]

Now the first situation works fine, however when I try prompt with no arguments, it asks for user input, but when I enter it, it seg faults and I'm not sure why.

This is the code I have so far:

void prompt(char *target)
{
    if(!target)
    {
        printf("Please enter a prefix: ");
        scanf("%s", &target);
    }
    char *result = malloc(strlen(SHELL) + strlen(target) + 1);
    strcpy(result, target);
    strcat(result,  SHELL);
    SHELL = result;
}

Any ideas?? Maybe it is just a simple mistake on my part but it seems like this should work.

By the way, in my code, "SHELL" is just a macro for a char arrray that is "[MY_SHELL]: ".

Was it helpful?

Solution

The problem is with this statement:

scanf("%s", &target);

You need to pass in a pointer to a buffer for the input string, not a pointer to a char *. Replace it with something like:

target = (char *)malloc(1000);
scanf("%s", target);

Of course, this is not secure code since the user's input could exceed 1000 characters. But let's get the basics right first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top