2015-09-28 109 views
0

我正在C中創建一個哈希表,其鍵的類型爲char *。我將該密鑰存儲在表中,原因不在此問題的範圍之內。散列表大部分工作,除了以下問題:當表大小超過2112個元素,並嘗試將鍵初始化爲NULL指針時,我遇到了分段錯誤。循環分配內存時出現分段錯誤

這裏是Hashtable的定義:

typedef struct hash_table 
{ 
    uint32_t size; // # of elements the table can store 
    uint32_t count; // # of elements in the table 
    char **keys; // The pointer to the first key. Each key is a char* 
    int32_t *vals; // The pointer to the first val. 
} hashTable; 

這裏是我用NULL指針初始化表作爲鍵:

// Declare the pointer to the hash table 
hashTable *symbolTable = malloc(sizeof(hashTable)); 

// Set the hash table properties 
symbolTable->size = 7699; 
symbolTable->count = 0; 
symbolTable->keys = malloc(sizeof(symbolTable->keys[0]) * symbolTable->size); 
symbolTable->vals = malloc(sizeof(symbolTable->vals[0]) * symbolTable->size); 

// Initialize the keys to be NULL pointers. 
int i; 
for (i = 0; i < symbolTable->size; i++) 
{ 
    char **cp = symbolTable->keys + i * sizeof(symbolTable->keys[0]); 
    *cp = NULL; 
} 

當我運行程序時,我得到一個分割在i == 2111時for循環出錯。

我對C中的動態內存分配比較陌生,並且一直在這個問題上停留了一段時間。如果有人有任何見解或建議,我將不勝感激。

回答

6

設置cp時,不需要將i乘以sizeof。指針運算自動乘以指針指向的對象的大小。結果就是你倍增了兩倍,所以你寫的遠在數組邊界之外。所以它應該是

char **cp = symbolTable->keys + i; 

但你完全可以正常使用數組索引來代替:

symbolTable->keys[i] = NULL; 
+0

這兩項解決方案的工作。謝謝您的幫助。 –