我有一個「名稱」(字符串)字段的有序結構列表(CASE)。我想用參數「name」(string)和「count」(integer)創建一個新的結構體(ARTCOUNT)。試圖將數據從一個結構複製到另一個結構時出現分段錯誤
的Structs:
typedef struct
{
char* name;
char* art;
int rating;
}CASE;
typedef struct
{
char* name;
int count;
}ARTCOUNT;
我會走的CASE陣列,如果「名」的情況下,ARTCOUNT相匹配的名字,我會加1計數,否則我將創建一個新的ARTCOUNT陣列新的名字,並繼續走陣列。
我遇到的問題是一個奇怪的分段錯誤,當我嘗試添加到計數名稱匹配。
/*all is the array of CASE and pLast points to the last CASE in all*/
void countArt(CASE* all, CASE* pLast)
{
CASE* walker = all;
ARTCOUNT* artAll;
ARTCOUNT* artWalker = artAll;
ARTCOUNT* artLast;
if((artAll = (ARTCOUNT*)malloc(sizeof(ARTCOUNT)*(pLast-all+1))) == NULL)
{
printf("Fatal memory error!\n");
exit(1);
}
artWalker->name = (char*)malloc(sizeof(char)*(100));
strcpy(artWalker->name, walker->name);
artWalker->count = 1;
for(walker = all+1; walker <= pLast; walker++)
{
if (strcmp(walker->name, artWalker->name) == 0)
{
artWalker->count += 1;
}
else
{
artWalker++;
artWalker->name = (char*)malloc(sizeof(char)*(100));
strcpy(artWalker->name, walker->name);
artWalker->count = 1; //if I comment this out, no segmentation fault
}
}
artLast = artWalker;
return;
}
如上代碼上面提到的,我設法縮小可能是什麼錯誤行artWalker->count-1;
。如果我註釋掉這一行,錯誤消失。但是,如果我嘗試在循環中打印artWalker->名稱,我仍然會收到分段錯誤。我檢查過我的內存分配幾次,我不認爲這是。
任何提示?
嗯..我不認爲這會影響我分配artWalker。當我爲artAll分配內存時,它是否指向artAll分配的數組? – Huy 2012-04-24 16:22:39
@hyngyn不,'artWalker'在'malloc'調用後仍然會有'artAll'的舊無效值 – ouah 2012-04-24 17:38:05
感謝您的幫助! – Huy 2012-04-24 17:43:36