Reputation: 95
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.
In the for-loop I am checking how many spaces there are, which determines how many words there are in total (spacing is always N-1, N = number of words). Then I tell the program to add 1 to the counter (Because of N-1).
I declare a char* array[] in order to keep each of the individual words seperated, not sure if I need counter+1 here (because of the \0?)
This is where the tricky part comes in. I use strtok to seperate each words (using " "). I then malloc each position of char*array[] so that it has enough memory to store the words. This is done until there are no more words to put in.
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
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