Search code examples
ccharsegmentation-faultstrtokdereference

Segmentation Error using strtok


Trying to split a string using delimiter " " using strtok, but I am getting a segmentation error.

    char command[12];
    char *instruction;
    char *parameter_1;
    char *parameter_2;
    *instruction = strtok(command, " ,.-");
    *parameter_1 = strtok(NULL, " ,.-");
    *parameter_2 = strtok(NULL, " ,.-");
    write(1,parameter_1,sizeof(parameter_1));

at the point in th

EDIT: As requested, compiler warnings. Not using int anywhere, so confused.

shell.c:51:16: warning: assignment makes integer from pointer without a cast [enabled by default]
shell.c:52:16: warning: assignment makes integer from pointer without a cast [enabled by default]
shell.c:53:16: warning: assignment makes integer from pointer without a cast [enabled by default]

Command: abd def ghj
Segmentation fault (core dumped)

EDIT 2:

int prompt() {
    // Get Input
    char inputData[256];
    int rid;
    rid = read(0,inputData,256);

    // Strip input
    char command[rid];
    int i;
    for (i = 0; i<=rid-2; i++) {
        command[i] = inputData[i];
    }
    command[rid-1] = '\0';

    // Debug
    //  printf("\n-%c-%i\n",command[10],(int)sizeof(command));
    //  write(1,command,sizeof(command));

    if (strcmp(command, "exit") == 0) {
        break;
    }

    char *instruction;
    char *parameter_1;
    char *parameter_2;
    instruction = strtok(command, " ");
    parameter_1 = strtok(NULL, " ");
    parameter_2 = strtok(NULL, " ");
    write(1,instruction,sizeof(instruction));
    //write(1,parameter_2,sizeof(parameter_2));
}

return 0;

}


Solution

  • Fix as follows:

    char command[12];
    char *instruction;
    char *parameter_1;
    char *parameter_2;
    instruction = strtok(command, " ,.-");
    parameter_1 = strtok(NULL, " ,.-");
    parameter_2 = strtok(NULL, " ,.-");
    write(1,parameter_1,sizeof(parameter_1));
    

    (Removed the *)