【发布时间】:2015-03-28 18:43:16
【问题描述】:
我正在尝试实现的一个小哈希表的表格有问题。
地图.h
typedef struct Map Map;
Map *map_create();
int map_set(Map *map, char *key, void *val);
地图.c
const int MAP_INITIAL_SIZE = 100;
typedef struct MapPair MapPair;
struct MapPair
{
char *key;
void *val;
};
struct Map
{
MapPair **table;
int count;
int limit;
};
Map *map_create(void)
{
Map *map = (Map*)malloc(sizeof(Map));
if (!map) return NULL;
map->table = (MapPair**)malloc(MAP_INITIAL_SIZE * sizeof(MapPair));
if (!map->table)
{
free(map);
return NULL;
}
map->count = 0;
map->limit = MAP_INITIAL_SIZE;
return map;
}
void add(MapPair **context, int start, MapPair *pair, int limit)
{
int i = start;
while (context[i] != NULL && strcmp(context[i]->key, pair->key) != 0) // crashing here
{
i++;
if (i == limit) i = 0;
}
context[i] = pair;
}
int map_set(Map *map, char *key, void *val)
{
if (map->count >= map->limit / 2)
{
if (!expand(map)) return 0;
}
MapPair *pair = (MapPair*)malloc(sizeof(MapPair));
if (!pair) return 0;
pair->key = key;
pair->val = val;
add(map->table, hash(key, map->limit), pair, map->limit);
++map->count;
return 1;
}
我最初是在 pelles c 中开发的,但是当我遇到问题时,我转移到了 vs2013 的调试器。然后在 vs2013 中,程序会在 add 函数处崩溃,但在 pelles c 中不会。我假设它与我计划稍后扩展的动态数组有关。
谁能告诉我为什么当我尝试访问动态数组的索引时程序似乎崩溃了?
【问题讨论】:
-
函数expand()和hash()定义在什么头文件中?
-
看来你的一级间接太多了。您的
Map应该包含MapPair *,并且您应该使用context[i].key访问这些字段。 (您对map->table的分配反映了这种模式。您还可以在哈希映射中存储指向对的指针,但这会引入额外的内存管理。) -
@codefrenzy 相同的标头,我省略了它们以尽量减少代码量。我什至没有进入扩展部分。
-
您不会将
map->table初始化为所有NULLs,从而取消引用垃圾指针。不初始化会使(主要有用的)检查NULL无用。 -
@CarsonEvans: 是的,但你可以让他们有一个
NULL键,例如。