免费的char *:无效的下一个尺寸(快) [英] free char*: invalid next size (fast)
问题描述
我是一个串联过程后释放一个char *。结果
但我收到此错误:
免费():无效的下一个尺寸(快):0x0000000001b86170
块引用>下面是我的code:
无效CONCAT(StringList的*名单){
字符*解析度=(字符*)malloc的(sizeof的(字符*)); 的strcpy(RES,列表 - >流浆>字符串); 列表 - > TMP =列表 - >流浆>接下来,
而(列表 - > TMP!= NULL){
的strcat(水库,,);
strcat的(资源,列表 - > tmp->字符串);
列表 - > TMP =列表 - > tmp->接下来,
} 的printf(%S \\ n,RES); 免费(RES);
}
解决方案您code是错误的。
您为单一指针分配空间(
的malloc(sizeof的(字符*))
),但没有文字。您正在使用的所有字符串覆盖你分配的空间,从而导致未定义的行为(在tihs特定情况下,破坏的malloc()
的簿记数据)。您不必为指针(
RES
)分配空间,这是一个局部变量。您的必须的您希望在由指针中保存的地址存储的所有字符分配空间。因为你将要遍历一个列表中查找的字符串来连接,你可以不知道总规模的前期。你将有超过列表做两遍:一是总结了
的strlen()
每个字符串
,然后分配该加的空间分隔和终止,接着又传当你真正做concatenenation。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); }
解决方案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, corruptingmalloc()
'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 eachstring
, then allocate that plus space for the separator and terminator, then another pass when you actually do the concatenenation.这篇关于免费的char *:无效的下一个尺寸(快)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!