0
votes

So i am trying to read lines and then split them in two with strtok . So if i would read "nice dog" it will first print what i read and then will print using the strtok commands "nice" and "dog" on the next line . But after second input i got Segmentation fault .Also , what does free(buf) do ? I've seen that the error is at this line : "strcpy(name, strtok(NULL, " "));" This is the code :

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *buf;
    char command[32];
    char name[32];

    while((buf = readline("\n"))!=NULL)
    {
        if (strcmp(buf,"exit")==0)
            break;

        printf("%s\n",buf);

        strcpy(command, strtok(buf, " "));
        printf("%s\n", command);
        strcpy(name, strtok(NULL, " "));
        printf("%s\n", name);
        if(buf[0]!=NULL)
        add_history(buf);
    }
    free(buf);
    return 0;
}
1
What does readline do?Some programmer dude
Check your strtok output before using it.Eugene Sh.
reads your line inputaNNgeL0
Free deallocates the memory that you get from the heap, so using malloc or one of the relating functions. Whenever you malloc something you have to free it otherwise you will have memory leaksuser3282276
readline may be buggy. it's clearer if you show us the code of readline.Jason Hu

1 Answers

1
votes

You must check the result of strtok if it's NULL meaning that no tokens where found you will get segmentation fault

char *pointer;
pointer = strtok(buf, " ");
if (pointer != NULL)
    strcpy(command, pointer);

also, readline allocates new memory on every call so you should free inside the while loop.

Fix it this way

#include <stdio.h>
#include <stdlib.h>

#include <readline/readline.h>
#include <readline/history.h>

int main()
{
    char *buf;
    char command[32];
    char name[32];

    while((buf = readline("\n"))!=NULL)
    {
        char *pointer;
        if (strcmp(buf,"exit")==0)
            break;

        printf("%s\n",buf);

        pointer = strtok(buf, " ");
        if (pointer != NULL)
        {
            strcpy(command, pointer);
            /* Don't print poitner otherwise since it is unintialized */
            printf("%s\n", pointer);
        }

        /* subsequent calls to strtok must have first argument NULL */
        pointer = strtok(NULL, " ");
        if (pointer != NULL)
        {
            strcpy(name, pointer);
            printf("%s\n", pointer);
        }

        if (buf != NULL) // this is never FALSE because of the while condition
            add_history(buf);
        free(buf);
    }
    return 0;
}

you also have to make sure that command and name will be big enough to fit the resulting stirng.