c - hashmap 的动态数组访问冲突

标签 c arrays dynamic hashmap

我在尝试实现一个小 HashMap 的表时遇到问题。

map .h

typedef struct Map Map;

Map *map_create();
int map_set(Map *map, char *key, void *val);

map .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 中不会。我假设它与我计划以后能够扩展的动态数组有关。

谁能告诉我为什么当我尝试访问动态数组的索引时程序似乎崩溃了?

最佳答案

在 add 函数中,您正在检查表,直到到达 NULL 指针:

while (context[i] != N ...

但是当您分配这个表时,您永远不会将这些指针中的任何一个设置为 NULL:

map->table = (MapPair**)malloc(MAP_INITIAL_SIZE * sizeof(MapPair));

您应该将它们设置为 NULL:

for( size_t i = 0 ; i < MAP_INITIAL_SIZE ; i++ )
    map->table[i] = NULL ;

否则你将超出该数组的范围。

关于c - hashmap 的动态数组访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28216429/

相关文章:

c - 如何使用C下载网页内容?

c - 使用 gdb 调试链接库中的函数时遇到问题

C# 从数组中获取数据,就像我在 php 中一样

python - Numpy:就地操作和显式操作的奇怪不同行为

c++ - C++ 栈中的数组

ios - 动态表格 View 单元格,防止创建自动高度约束

检查 ISBN 以查看其在 C 语言中是否有效

python - 如何创建包含 ppm 图像的二进制光栅数据的 C 字符串

javascript - 控制 Meteor.js 中动态加载的脚本

dynamic - RollingFileAppender 中动态文件命名的 log4net 问题