Domanda

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;

}

È stato utile?

Soluzione 2

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 *)

Altri suggerimenti

As I posted in comments:

*instruction = strtok(command, " ,.-");
*parameter_1 = strtok(NULL, " ,.-");
*parameter_2 = strtok(NULL, " ,.-");

should be relaced with

instruction = strtok(command, " ,.-");
parameter_1 = strtok(NULL, " ,.-");
parameter_2 = strtok(NULL, " ,.-");

Also sizeof(instruction) doesn't return number of characters( it's not an array) but size of pointer to char (that's what instruction, param_1, param_2 really are) on your machine.

As answer to OP comment:
write() or fwrite() work on bytes, without checking its meanings so they don't stop on '\0'.
fprintf(), fputs() are prepared to work on strings so they check for '\0' char to stop.

command is a string literal, it is in ROM. copy it to a local variable maybe using memcpy() and then use it in strtok().

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top