【发布时间】:2016-02-21 21:35:07
【问题描述】:
我有一个节点,我定义它的全局指针变量如下:
typedef struct node
{
char* word;
struct node* next;
} node;
node* HashTable = NULL;
node* HeadOfHashTable = NULL;
现在,我分配的内存如下:
void allocateMemory(int numOfElements, bool isRealloc, const char* word)
{
if(!isRealloc)
{
printf("Allocating %d blocks\n", numOfElements);
HashTable = malloc(sizeof(node*) * numOfElements);
} else {
printf("Reallocating %d blocks for %s", numOfElements, word);
HashTable = realloc(HashTable, sizeof(node*) * numOfElements);
}
if(HashTable == NULL)
{
printf("### Out Of Memory ###\n");
exit(0);
}
HeadOfHashTable = HashTable;
}
现在,我在下面的方法中传递一个 HASH 值和单词以放入哈希表中。我已经评论了我遇到段错误的地方。
void putInHashTable(char* ch, unsigned int hashValue)
{
HashTable += hashValue;
printf("Processing at address: %p and has value was %d\n", HashTable, hashValue);
if(HashTable == NULL || HashTable == '\0' || HashTable == 0)
{
printf("Hash table is NULL");
}
if(HashTable->word == NULL)
{
HashTable->word = malloc(sizeof(char) * (LENGTH + 1));
strcpy(HashTable->word, ch);
printf("New word: %s\n", HashTable->word);
} else {
printf("### Collision detected ###\n"); // ***** BELOW LINE GIVES SEG FAULT ******
printf(" Earlier value is %s, new value is %s and its pointer is %p\n", HashTable->word, ch, HashTable->next);
putInLinkedList(ch);
}
HashTable = HeadOfHashTable;
}
以下是控制台日志:
Allocating 65336 blocks
Processing at address: 0xb7568c28 and has value was 388
New word: a
Processing at address: 0xb756b9a0 and has value was 1843
New word: aaa
Processing at address: 0xb7570c08 and has value was 4480
New word: aaas
Processing at address: 0xb75ae608 and has value was 36032
### Collision detected ###
Segmentation fault (core dumped)
我的疑惑:
- 我正在分配 65336 个内存块,而我遇到段错误的点的哈希值为 36032,因此我确信指针变量
HashTable具有有效的内存地址。那为什么会出现段错误? - 如果它不是一个有效的地址,那么为什么它没有在这个 IF 条件
if(HashTable == NULL || HashTable == '\0' || HashTable == 0)中被捕获。我什至使用了calloc然后我也遇到了 seg 错误并且上面的 IF 条件没有被捕获。 - 我在这条线
printf(" Earlier value is %s, new value is %s and its pointer is %p\n", HashTable->word, ch, HashTable->next);遇到了段错误。这意味着在取消引用指针时出现了一些问题,那么为什么在此之前我没有遇到段错误,这意味着我应该只在这里遇到段错误 -if(HashTable->word == NULL)?
【问题讨论】:
-
if(HashTable == NULL || HashTable == '\0' || HashTable == 0)如果您不确定如何检查 NULL,请询问 stackoverflow。我们随时为您提供帮助! -
sizeof(node*)-->sizeof(node) -
您的调试器会告诉您崩溃发生的位置。
-
HashTable = malloc(sizeof(node*) * numOfElements);==>HashTable = malloc(sizeof *HashTable * numOfElements); -
@hagrawal 实际上,您的调试器会告诉您的不仅仅是崩溃发生的地方。了解如何使用它,它将为您节省大量时间。
标签: c pointers segmentation-fault