设置调整大小时的内存错误

时间:2015-06-14 09:43:15

标签: c memory-management

这是我写过的一套结构:

struct state_set
{
    struct state ***state_array;
    size_t *slot_sizes;
    size_t *slot_memory;
};

这是一个初始化程序:

struct state_set *state_set_init()
{
    struct state_set *new_set =
            malloc(sizeof(struct state_set));
    new_set->state_array = malloc(ARRAY_SIZE * sizeof(struct state**));
    new_set->slot_sizes = malloc(ARRAY_SIZE * sizeof(size_t));
    new_set->slot_memory = malloc(ARRAY_SIZE * sizeof(size_t));
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        new_set->slot_sizes[i] = 0;
        new_set->slot_memory[i] = INITIAL_SLOT_SIZE;
    }
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        new_set->state_array[i] =
                malloc(new_set->slot_memory[i] * sizeof(struct state*));
        error_validate_pointer(new_set->state_array[i]);
    }

    return new_set;
}

还有一个导致内存错误的大小调整功能:

void state_set_resize_slot(struct state_set *set, int slot_i)
{
    struct state **to_resize = set->state_array[slot_i];
    to_resize =
            realloc(to_resize, set->slot_memory[slot_i] * 2 * sizeof(struct state*));
    error_validate_pointer(to_resize);
    set->slot_memory[slot_i] *= 2;
}

问题是 - 为什么state_set_resize_slot()无效?我无法看到这个realloc有任何错误,而且我已经盯着这段代码至少一个小时了。 (显然,realloc是造成我所有麻烦的原因)。或者也许调整大小功能写得很好,我应该在其他地方寻找错误?

编辑:

如果有人想要查看完整代码,请点击此处: http://pastebin.com/bfH3arDi(哈希函数返回1而不是h,因为我测试了冲突,初始化器和析构函数也已过时,现在我正在使用slot_memory和slot_sizes的数据来代替使用栈)。

这是运行程序的valgrind输出,它添加了几个要设置的状态(错误大约是第三次调整大小):

==20979== Invalid write of size 8
==20979==    at 0x400C21: state_set_add (state_set.c:93)
==20979==    by 0x400781: main (main.c:22)
==20979==  Address 0x51f2320 is 0 bytes inside a block of size 40 free'd
==20979==    at 0x4C2BB1C: realloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==20979==    by 0x4009CD: state_set_resize_slot (state_set.c:54)
==20979==    by 0x400B23: state_set_add (state_set.c:78)
==20979==    by 0x400781: main (main.c:22)
==20979== 
==20979== Invalid free() / delete / delete[] / realloc()
==20979==    at 0x4C2BB1C: realloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==20979==    by 0x4009CD: state_set_resize_slot (state_set.c:54)
==20979==    by 0x400B23: state_set_add (state_set.c:78)
==20979==    by 0x4007B2: main (main.c:23)
==20979==  Address 0x51f2320 is 0 bytes inside a block of size 40 free'd
==20979==    at 0x4C2BB1C: realloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==20979==    by 0x4009CD: state_set_resize_slot (state_set.c:54)
==20979==    by 0x400B23: state_set_add (state_set.c:78)
==20979==    by 0x400781: main (main.c:22)
==20979== 
a.out: state_set.c:20: error_validate_pointer: Assertion `ptr != ((void *)0)' failed.

1 个答案:

答案 0 :(得分:2)

在你的函数中,你将指针指向to_resize,然后指向内存realloc,但是你永远不会将新指针设置回set->state_array[slot_i],所以它会丢失而你继续使用旧的,已经释放的内存空间,并指出它的界限。