Question

I'm looking to separate a line (given as one string) into words. for example: " Hello world". I can have one or more tabs or spaces between the words and in the beginning. I'm trying to do something like this: (findCommand is a function and line is the string I get as input, for this part I only need the first 2 words)

CommandResult findCommand (const char* line){
    char* commandLine = malloc(strlen(line)+1);
    strcpy(commandLine, line);
    char space[] = " \t";
    char* word1 = strtok(commandLine,space);
    char* word2 = strtok(NULL,space);

I've tried to run this in Eclipse with different variations of spaces and tabs. some of them worked fine, on others I get a sigmentation fault and I can't figure out why.

Was it helpful?

Solution

This:

char* commandLine = malloc(sizeof(strlen(line)));

is wrong. You shouldn't use sizeof here, and certainly not on the result of calling strlen(). The above is the same as:

char *commandLine = malloc(sizeof (size_t));

since the return type of strlen() is size_t. Thus, the actual strlen() return value is ignored.

The proper code is:

char *commandLine = malloc(strlen(line) + 1);

since you must add 1 for the terminator, which is not included in the length returned by strlen().

There is no need for any sizeof here, since you're very obviously working with characters.

OTHER TIPS

Use malloc((strlen(line) + 1)* sizeof(char)) instead of malloc(sizeof(strlen(line))). You allocate only space for an integer because sizeof returns an integer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top