Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 空闲字符*:下一个大小无效(快速)_C_Malloc_Free - Fatal编程技术网

C 空闲字符*:下一个大小无效(快速)

C 空闲字符*:下一个大小无效(快速),c,malloc,free,C,Malloc,Free,我在串联过程后释放一个字符*。 但我收到了这个错误: 自由:无效的下一个快速大小:0x0000000001b86170 下面是我的代码: void concat(stringList *list) { char *res = (char*)malloc(sizeof(char*)); strcpy(res, list->head->string); list->tmp = list->head->next; while (list

我在串联过程后释放一个字符*。 但我收到了这个错误:

自由:无效的下一个快速大小:0x0000000001b86170

下面是我的代码:

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);
}
你的代码错了

您正在为单指针mallocsizeofchar*分配空间,但没有字符。您正在用所有字符串覆盖分配的空间,在特定情况下会导致未定义的行为,从而损坏malloc的簿记数据

您不需要为指针res分配空间,它是一个局部变量。必须为要存储在指针所持地址的所有字符分配空间

由于要遍历列表以查找要连接的字符串,因此无法预先知道总大小。您必须在列表上进行两次传递:一次对每个字符串的strlen求和,然后为分隔符和终止符分配加上的空间,然后在实际执行concateneration时进行另一次传递。

您的代码是错误的

您正在为单指针mallocsizeofchar*分配空间,但没有字符。您正在用所有字符串覆盖分配的空间,在特定情况下会导致未定义的行为,从而损坏malloc的簿记数据

您不需要为指针res分配空间,它是一个局部变量。必须为要存储在指针所持地址的所有字符分配空间


由于要遍历列表以查找要连接的字符串,因此无法预先知道总大小。您必须在列表上进行两次传递:一次对每个字符串的strlen求和,然后为分隔符和终止符分配加上的空间,然后在实际执行concateneration时进行另一次传递。

成功了。谢谢你提供的信息,一切正常。谢谢你的信息。