簡體   English   中英

循環遍歷分配的內存時出現分段錯誤

[英]Segmentation Fault when Looping over Allocated Memory

我正在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進行動態內存分配相對較新,並且在此問題上停留了一段時間。 如果有人有任何見解或建議,我將不勝感激。

設置cp ,不需要將i乘以sizeof 指針算術自動乘以指針指向的對象的大小。 結果是您要進行兩次乘法運算,因此您所寫的內容遠遠超出了數組范圍。 所以應該

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

但是您可以簡單地使用普通數組索引:

symbolTable->keys[i] = NULL;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM