free char*: invalid next size (fast) [duplicate]

好久不见. 提交于 2019-12-17 03:44:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!