Reputation: 285
I want to split my char string by space and here is my code.(reference to others)
void main() {
char origin_str[] = "How are you";
int n_segs = Words_counts(origin_str);
char **split_array = malloc(n_segs * sizeof(char*));
split_array = split_str_to_array(origin_str);
..... //do something
free(split_array);
}
and the split_str_to_array function:
char **split_str_to_array(const char strr[]) {
char **res = NULL;
char * p = strtok(strr, " ");
int n_spaces = 0;
while (p) {
res = realloc(res, sizeof(char*) * ++n_spaces);
if (res == NULL)
exit(-1);
res[n_spaces - 1] = p;
p = strtok(NULL, " ");
}
res = realloc(res, sizeof(char*) * (n_spaces + 1));
res[n_spaces] = 0;
return res;
}
It works well, butI'm confused with the usage of getting char array from the split_str_to_array function.
Should I use free(res) in the split function?If yes, how do I return the char array? Declaring a new one with known length to return?
I'm afraid of memory using problems in the split function. Or, a better way to do the same?
very appreciated for your help.
Upvotes: 0
Views: 64
Reputation: 70971
The usage of free()
is correct.
Free what you allocated if not needed any more, by passing to free()
what had been returned by the allocating function.
However the allocation in main()
is useless
char **split_array = malloc(n_segs * sizeof(char*));
as in the next line
split_array = split_str_to_array(origin_str);
you overwrite what had been assigend to split_array
.
Doing so you lose what had been returned by malloc()
so you cannot free it anymore and with this introduce a memory leak.
Upvotes: 1