Question

Hey I was wondering if anyone knew how to solve this problem. I want to grab user input and from that preform some operations off that. Right now I am getting a segfault on a scanf line and can't figure out why. After that I am trying to concatenate the two arrays together and help with that would be great also.

char command[1000];
char firstName[1000];
char lastName[1000];
char month[1000];
char day[1000];

while( strcmp("quit", &command[0]) != 0 ){
    fflush(stdin);

    printf("Please enter next command: ");
    scanf("%s", command);                    // <--- This is tested and working

    if(strcmp(&command[0], "quit") == 0){
        break;
    }

    else if(strcmp(&command[0], "empty") == 0){
        empty();
    }
    else if(strcmp(&command[0], "append") == 0){
        printf("--------->1");

        scanf("%s %s %s %s", firstName, lastName, month, day); //<--- This line :(

        printf("--------->2");  // <---- This never prints
        char fullName[2001];
        char birthday[2001];

        malloc(strlen(firstName) + 1);
        strcpy(firstName, fullName);

        malloc(strlen(lastName) + 1);
        strcpy(lastName, fullName);
        printf("%s", fullName);

From the terminal:

gregs-mbp:desktop GregR$ ./blist
Please enter next command: append greg r jan 02
Segmentation fault: 11
gregs-mbp:desktop GregR$ ./blist
Please enter next command: append     
--------->1greg r jan 02
Segmentation fault: 11
gregs-mbp:desktop GregR$ 
gregs-mbp:desktop GregR$ ./bList
Please enter next command: quit
All done
Was it helpful?

Solution

There is no problem with scanf in your code. The problem is in code

    char fullName[2001];
    char birthday[2001];

    malloc(strlen(firstName) + 1);
    strcpy(firstName, fullName);

    malloc(strlen(lastName) + 1);
    strcpy(lastName, fullName);
    printf("%s", fullName);

this should be something like

    char fullName[2001];
    char birthday[2001];

    strcpy(fullName,firstName);
    strcat(fullName,lastName);

    printf("%s", fullName);

Example of working program: http://ideone.com/dvpHYL

I believe that segfault was caused by reversed arguments of strcopy. There probably was some arbitrary data in fullName (as it was not initialized before), and while trying to copy it to firstName (which has smaller size) data was written beyond the bounds. mallocs was not necessary also, but they should not cause segfaults, only memory leaks.

OTHER TIPS

sscanf(command,"%s %s %s %s %s\n", cmdstring, firstName, lastName, month, day);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top