c - Seg faulting when getting user input? -


so building shell , 1 command implementing prompt. take argument , set prompt, if no argument entered ask user input , use that..... that's worded terribly here's example:

[shell] prompt code code[shell] ls code[shell] .... 

or

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

now first situation works fine, when try prompt no arguments, asks user input, when enter it, seg faults , i'm not sure why.

this code have far:

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

any ideas?? maybe simple mistake on part seems should work.

by way, in code, "shell" macro char arrray "[my_shell]: ".

the problem statement:

scanf("%s", &target); 

you need pass in pointer buffer input string, not pointer char *. replace like:

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

of course, not secure code since user's input exceed 1000 characters. let's basics right first.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -