【发布时间】:2015-07-09 15:57:50
【问题描述】:
我是 C 新手,但在指针和值方面遇到了一些问题。
所以我正在制作一个哈希表,我的插入函数出现错误(错误发布在代码之后):
typedef struct WordList {
char *word;
struct WordList *next;
} WordList;
typedef struct HashTable {
int key;
struct WordList *value;
struct HashTable *next;
} HashTable;
#define TABLE_SIZE 8192
HashTable *table[TABLE_SIZE] = { NULL };
//Insert element
void insertElement(int key, char *word) {
int i = 0;
// check if key has already existed
while((&(table[i]->key) != NULL) && (i < TABLE_SIZE)) {
// !!!! ERROR HERE !!!! if(table[i]->key == key) { // if find key
// ... implementation
return; // exit function and skip the rest
}
i++; // increment loop index
}
// find a NULL slot and store key and value
if(&(table[i]->key) == NULL) {
// !!! ERROR HERE!!! table[i]->key = key;
// ... implementation
}
}
int main() {
// test call
insertElement(1, "blah\0");
int i;
for ( i=0; i < 10; i++)
{
printf("%d: ", i);
struct HashTable *tableTemp = table[i];
while (tableTemp != NULL)
{
printf("(%d)\n", tableTemp->key);
tableTemp = tableTemp->next;
}
printf("\n");
}
return 0;
}
我使用 valgrind,这是分配表 [i]-> key = key 的错误
Invalid write of size 4
Address 0x0 is not stack'd, malloc'd or (recently) free'd
【问题讨论】:
-
地址
0x0为空指针;您正在尝试使用空指针写入一个 4 字节的值(可能是int)。喜欢int *p = 0; *p = 1;。 -
你在哪里为
table[i]分配内存?数组table是一个指针 数组,你初始化为NULL,如果你不让它们指向任何有效的内存,你就会得到那个错误。 -
为什么不只分配表[大小] 并使用点表示法?否则你必须 malloc 每个。