[問題] 大約一半機率會記憶體錯誤的字串處理函式
這個 function 主要是將自己寫的 Key&Value struct link list
串成一個 QueryString
大約一半機率會發生如下錯誤:
*** Error in
`/home/lky/workspace/*******************': free():
invalid next size (normal): 0x00000000021297e0 ***
想請版友幫忙診斷一下,是不是哪邊記憶體處理有缺失?
//用來組合 QueryString 的 node
struct listKeyValuePair
{
char* strKey;
char* strValue;
//Link list
struct listKeyValuePair* perv;
struct listKeyValuePair* next;
};
//用來把 listKeyValuePair 已經串起的整個 Link List 轉換成單一 QueryString
char* ConvertToQueryString(struct listKeyValuePair* node)
{
char* strQueryString = (char*)calloc(sizeof(char),0);
while(NULL != node)
{//一個接一個按照QueryString格式串上去
size_t newLength =
strlen(strQueryString)+strlen(node->strKey)+strlen(node->strValue)+3;
strQueryString = (char*)realloc(strQueryString, newLength);
if(NULL == node->perv)
{//第一個
sprintf(strQueryString, "%s=%s",node->strKey,
node->strValue);
}
else
{//第二個以後
sprintf(strQueryString, "%s&%s=%s", strQueryString,
node->strKey,
node->strValue);
}
node = node->next;
}
//puts(strQueryString);
return strQueryString;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.205.43
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1475725074.A.177.html
→
10/06 11:46, , 1F
10/06 11:46, 1F
因為想要確保是'\0'結尾空字串,不然會是亂七八糟的內容
→
10/06 11:48, , 2F
10/06 11:48, 2F
※ 編輯: deo2000 (125.227.205.43), 10/06/2016 11:49:43
→
10/06 11:52, , 3F
10/06 11:52, 3F
推
10/06 12:02, , 4F
10/06 12:02, 4F
謝謝,照改之後就不會記憶體錯誤了。但我現在還看不出原因?
但是改了以後QueryString就會無法串起,return 只會剩下最後那一對,也還在找原因
推
10/06 12:12, , 5F
10/06 12:12, 5F
→
10/06 12:12, , 6F
10/06 12:12, 6F
因為想把他寫得有彈性,看list多長字串就長到哪裡
※ 編輯: deo2000 (125.227.205.43), 10/06/2016 12:29:30
→
10/06 12:30, , 7F
10/06 12:30, 7F
free 掉就沒有東西可以 return 了耶?
※ 編輯: deo2000 (125.227.205.43), 10/06/2016 12:33:01
※ 編輯: deo2000 (125.227.205.43), 10/06/2016 12:47:33
→
10/06 13:05, , 8F
10/06 13:05, 8F
就"\0"
→
10/06 13:11, , 9F
10/06 13:11, 9F
→
10/06 13:13, , 10F
10/06 13:13, 10F
※ 編輯: deo2000 (125.227.205.43), 10/06/2016 13:26:24
推
10/06 13:35, , 11F
10/06 13:35, 11F
→
10/06 13:36, , 12F
10/06 13:36, 12F
→
10/06 13:36, , 13F
10/06 13:36, 13F
→
10/06 13:37, , 14F
10/06 13:37, 14F
→
10/06 13:38, , 15F
10/06 13:38, 15F
→
10/06 13:38, , 16F
10/06 13:38, 16F
→
10/19 04:11, , 17F
10/19 04:11, 17F
討論串 (同標題文章)
完整討論串 (本文為第 1 之 2 篇):