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;
}
/*
and some words and then*/
. If you insert these "comments" into your code at various points it makes it far easier for you to understand what you're doing, and also makes it easier for other people.res
isNULL
terminatedstr
ever end with a space?