我正在为我的一门课程编写一个程序,所以如果答案保持抽象,我将不胜感激。我正在用C编写一个键值哈希表,该表存储一个键的字符串和一个值的int。我在put((方法的helper函数上遇到了分段错误。下面是有问题的代码。出于学术诚实的目的,我对其进行了轻微的更改,并且我只包括了导致错误的部分。我试着调整我取消引用或不取消引用table[index]->symbol
的方式,但没有用。我想SEGFAULT发生的那条线可能不是罪魁祸首,但我正在努力寻找它可能出现的地方。我们将非常感谢对此事的任何帮助,无论是GDB的提示、高级解释等。我只是要求代码片段保持模糊,以便我真正学习,而不仅仅是被告知答案。非常感谢。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct elem_t elem_t;
struct elem_t {
const char* symbol;
void* data;
elem_t* next;
};
typedef struct {
size_t length;
size_t size;
elem_t** table;
} table_t;
static unsigned int hash(const char *str) {
const unsigned int p = 16777619;
unsigned int hash = 2166136261u;
while (*str) {
hash = (hash ^ *str) * p;
str += 1;
}
hash += hash << 13;
hash ^= hash >> 7;
hash += hash << 3;
hash ^= hash >> 17;
hash += hash << 5;
return hash;
}
void *createTable(int sizeHint) {
table_t* table;
table = malloc(sizeof(table));
if (table == NULL) {
return NULL;
}
table->length = 0;
table->size = sizeHint * 2;
table->table = calloc(table->size, sizeof(elem_t*));
if (table->table == NULL) {
free(table);
return NULL;
}
return table;
}
static const char* putHelper(elem_t** table, size_t size, const char* symbol, void* data, size_t* length) {
unsigned int hashVal = hash(symbol);
size_t index = (size_t)(hashVal & (unsigned int)(size - 1));
while (table[index]->symbol != NULL) { // !!! SEGFAULT HERE !!!
if (strcmp(symbol, table[index]->symbol) == 0) { // collision
elem_t* cur = table[index];
while (table[index]->next != NULL) { // separate chaining
cur = cur->next;
}
elem_t* newElem = (elem_t*)malloc(sizeof(elem_t)); // make new element to hang at the end of the chain
cur->next = newElem;
newElem->data = data;
newElem->symbol = symbol;
newElem->next = NULL;
return newElem->symbol;
}
index++;
if (index >= size) {
index = 0;
}
}
if (length != NULL) {
symbol = strdup(symbol);
if (symbol == NULL) {
return NULL;
}
(*length)++;
}
table[index]->symbol = (char*)symbol;
table[index]->data = data;
return symbol;
}
int put(void *tableHandle, const char *symbol, void *data) {
table_t* table = (table_t*)tableHandle;
if (data == NULL) {
return 0;
}
table->length++;
const char* result = putHelper(table->table, table->size, symbol, data, &table->length);
if (result != NULL) {
return 1;
} else {
return 0;
}
}
int main() {
table_t* table = createTable(200);
int result = put(table, "t1", 25);
if (result == 0) {
printf("put failed");
return 1;
}
}
您分配了一个空指针数组
table->table = calloc(table->size, sizeof(elem_t*));
然后你使用空指针访问内存
while (table[index]->symbol != NULL) { // !!! SEGFAULT HERE !!!
^^^^^^^^^^^^^^^^^^^^
所以程序崩溃了。
正如@bbbbbbb所指出的,您只为指针分配了内存
table = malloc(sizeof(table));
您最不需要更改以下内容:
table_t* table;
table = malloc(sizeof(table));
对此:
table_t* table;
table = malloc(sizeof(*table));
或对此:
table_t* table;
table = malloc(sizeof(table_t));