I've written the following C function to split a string in a delimiter and return the word number "num_words":
void split_string(char *string, char **result, char *delimiter, int num_words){
long unsigned int cont_len = strlen(string);
char line[cont_len];
strcpy(line, string);
int i = 0;
char *tmp;
char *p = strtok (line, delimiter);
while ((p != NULL) & (i <= num_words)){
if (i == num_words){
*result = strdup(p);
break;
}
p = strtok (NULL, delimiter);
i = i+1;
}
free(p);
}
and in main:
char *string = "hello whole world";
char *result;
char *delimiter = " ";
int num_words = 2;
split_string(string, &result, delimiter, num_words);
In this example, split_string
would make result equal to "world". However, when I try to debug with gdb, I get a munmap_chunk(): invalid pointer
error originated in the free(p)
code line of the split_string
function.
I know that strdup
allocates memory, and that's why I was trying to free the p pointer. Where should I place this free? Should I only free(result)
in the main instead? I've read answers on similar stackoverflow questions, but none could solve my problem...