【发布时间】:2019-03-08 17:38:05
【问题描述】:
我不明白为什么我的程序在这一行出现段错误:if ((**table->table).link == NULL){ 我似乎有 malloc-ed 内存,我尝试用 gdb 查看它。 *table->table 可访问且不为 NULL,但 **table->table 不可访问。
hash_t的定义:
struct table_s {
struct node_s **table;
size_t bins;
size_t size;
};
typedef struct table_s *hash_t;
void set(hash_t table, char *key, int value){
unsigned int hashnum = hash(key)%table->bins;
printf("%d \n", hashnum);
unsigned int i;
for (i = 0; i<hashnum; i++){
(table->table)++;
}
if (*(table->table) == NULL){
struct node_s n = {key, value, NULL};
struct node_s *np = &n;
*(table->table) = malloc(sizeof(struct node_s));
*(table->table) = np;
}else{
while ( *(table->table) != NULL){
if ((**table->table).link == NULL){
struct node_s n = {key, value, NULL};
struct node_s *np = &n;
(**table->table).link = malloc(sizeof(struct node_s));
(**table->table).link = np;
break;
}else if (strcmp((**table->table).key, key) == 0){
break;
}
*table->table = (**(table->table)).link;
}
if (table->size/table->bins > 1){
rehash(table);
}
}
}
我从这里调用 set:
for (int i = 0; i < trials; i++) {
int sample = rand() % max_num;
sprintf(key, "%d", sample);
set(table, key, sample);
}
【问题讨论】:
-
这是很多取消引用。你为什么不告诉我们
hash_t的定义? -
你也应该告诉我们你是如何调用
set的,问题的根源可能在调用代码中。请阅读此:How to Ask 和此:minimal reproducible example -
当您有复杂的解引用表达式,并且您的代码中有错误时,请打开它。创建临时变量,一次做一个引用。如果您在编写该代码时没有发现问题,请在调试器下运行它,通常很容易找出您取消引用无效指针的确切位置。
-
使用调试器:单步调试代码并检查变量
标签: c pointers hash segmentation-fault malloc