LuftWoofe
LuftWoofe

Reputation: 95

Splitting a string into an array of words in C

I'm trying to make a function that splits a cstring into an array of words. Eg. if I send in "Hello world" then I'd get an array with two places where the 1st place has the element "Hello", second "world". I'm getting segmentation fault and I can't for the life of me figure out what seems to be wrong.

I would really appreciate it if someone could give me a hint of which part is causing the segmentation fault!

void split(char* s){

    int counter = 0;
    int pos = 0;

    for(int i=0; s[i]!='\0'; i++){
        if(s[i] == ' '){
            counter ++;
        }
    }
    counter += 1;

    char* array[counter+1];

    char *token = strtok(s, " ");

    while(token != NULL){
        array[pos] = malloc(strlen(token));
        strcpy(array[pos], token);
        token = strtok(NULL, " ");
        pos++;
    }

Upvotes: 1

Views: 1665

Answers (1)

P.P
P.P

Reputation: 121347

if I send in "Hello world" then I'd get an array with two places where the 1st place has the element "Hello", second "world".

No. You can't pass a string literal to that function. Because strtok() modifies its input. So, it'll attempt to modify string literal, resulting in undefined behaviour.

Be aware of the limitations of strtok(). From the man page of strtok():

   Be cautious when using these functions.  If you do use them, note
   that:

   * These functions modify their first argument.

   * These functions cannot be used on constant strings.

   * The identity of the delimiting byte is lost.

   * The strtok() function uses a static buffer while parsing, so it's
     not thread safe.  Use strtok_r() if this matters to you.

So, you need to pass a pointer to a modifiable memory location if you want to use strtok().


As BLUPIXY pointed out, your malloc() call doesn't allocate sufficient space. You need one more byte than the string length (for the terminating nul byte).

Upvotes: 3

Related Questions