问题
I am freeing a char* after a concatenation process.
But I receive this error:
free(): invalid next size (fast): 0x0000000001b86170
Below is my code:
void concat(stringList *list) {
char *res = (char*)malloc(sizeof(char*));
strcpy(res, list->head->string);
list->tmp = list->head->next;
while (list->tmp != NULL) {
strcat(res, ",");
strcat(res, list->tmp->string);
list->tmp = list->tmp->next;
}
printf("%s\n", res);
free(res);
}
回答1:
Your code is wrong.
You are allocating space for a single pointer (malloc(sizeof(char*))
), but no characters. You are overwriting your allocated space with all the strings, causing undefined behavior (in tihs particular case, corrupting malloc()
's book-keeping data).
You don't need to allocate space for the pointer (res
), it's a local variable. You must allocate space for all the characters you wish to store at the address held by the pointer.
Since you're going to be traversing a list to find strings to concatenate, you can't know the total size upfront. You're going to have to do two passes over the list: one to sum the strlen()
of each string
, then allocate that plus space for the separator and terminator, then another pass when you actually do the concatenenation.
来源:https://stackoverflow.com/questions/23008077/free-char-invalid-next-size-fast