2012-04-26 91 views
0

我很確定這是一個簡單的問題,但我想創建一個數據結構,實現動態數組結構。動態指針結構拋出指針SIGSEGV成員變量賦值

每個結構將實現一個鏈表。

所以我認爲我想要一個指針數組,它將指向每個列表的頭部。出於某種原因,分配方法變量給了我一個seg故障。如果可以的話,我會很樂意解釋我做錯了什麼。謝謝!所有這些都在一個名爲Cache的類中,所以這就是爲什麼有一些變量看起來沒有被定義,但我向你保證它們是。程序seg錯誤索引[i] - > next = NULL;和那個下面的類似的線。

 typedef struct setNode { 
    char valid, dirty; 
    unsigned int tag; 
    setNode *next; 
    Cache *nextCache; 

} set; 
    set **indexes; 

    arrayLength = cache_size/block_size; 

    indexes = new setNode *[arrayLength]; 

    set *temp; 

    //Step through the array. The array is full of pointers to "Dummy Nodes" 
    for (size_t i = 0; i < arrayLength; i++) { 
     indexes[i]->next = NULL; 
     indexes[i]->valid = 0; 
     indexes[i]->dirty = 0; 
     indexes[i]->tag = 0; 
     //create empty linked list for each tag spot (One for direct mapped. etc...) 

     for(size_t i = 0; i < associativity; i++) 
     { 
     temp = indexes[i]; 
     temp->next = new setNode; 
     temp = temp->next; 
     temp->next = NULL; 
     temp->valid = 0; 
     temp->dirty = 0; 
     temp->tag = 0; 
     } 

    } 

} 

回答

1

indexes是一個指針數組,以set對象,但它們是未初始化的。他們沒有指向實際的set對象,而僅僅指向隨機存儲器位置。嘗試寫入隨機存儲器是違反分段的真正原因。

使用指針之前,你需要分配set對象,使指針指向他們 - 即

for (size_t i = 0; i < arrayLength; i++) { 
    indexes[i] = new set; 
    indexes[i]->next = NULL; 
    indexes[i]->valid = 0; 
    ... 
+0

權,這是有道理的......我加索引[i] =新集;在for循環的頂部,現在它工作。謝謝!愚蠢的我,我沒有意識到你需要初始化結構和類,但由於數組只有指針,這是有道理的。 – usssrrrrrr1 2012-04-26 03:05:26