I am writing small IRC Bot, and i need to split incoming messages for easier handling. I wrote a function get_word, which should split string. According to gdb and valgrind, problem is that function sometimes returns invalid pointer, and program fails when trying to free that pointer.
Here is the code:
char **get_word(char *str) {
char **res;
char *token, *copy;
int size = 1;
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] == ' ') {
while(str[i] == ' ') {
i++;
}
size++;
}
}
res = malloc((size + 1) * sizeof(char *));
copy = strdup(str);
token = strtok(copy, " ");
for(int i = 0; token != NULL; i++) {
res[i] = strdup(token);
token = strtok(NULL, " ");
}
free(copy);
res[size] = NULL;
return res;
}
One problem I see is with your nested loops:
Consider this input:
' \0'The function execution reaches the
forloop,i == 0. Then thewhileloop is also entered. At the end ofwhileloopi == 1. Now the incrementation statement from theforloop is executed andi == 2. So next you will be reading past the end of the string.EDIT
I understand that
sizeis the number of words found in the input. So I’d go for something like: