【发布时间】:2015-01-22 20:45:47
【问题描述】:
我正在尝试使用动态数组来存储元素,但遇到了一个奇怪的错误。这是定义我的动态数组的代码:
#include "dtab.h"
#include "dbg.h"
#include <stdio.h>
dtab* dtab_create( void ) {
// Initialise un dtab*
// avec count = taille = tab = 0
return calloc(1, sizeof(dtab));
}
void dtab_push(dtab* t, void* value) {
if(t->taille == 0) { // Le tableau est vide
t->tab = malloc(sizeof(void*));
check_mem(t->tab);
t->tab[0] = value;
t->taille = 1;
t->count = 1;
} else if( t->taille == t->count) { // Le tableau est plein
t->taille *= 2;
printf("%zd", t->taille);
fflush(stdout);
t->tab = realloc(t->tab, t->taille);
check_mem(t->tab);
t->tab[t->count] = value;
t->count++;
} else {
t->tab[t->count] = value;
t->count++;
}
error:
return;
}
我可以使用这样的数组,但是当我尝试添加第五个元素时,因此当使用 t->taille == 8 调用 realloc 时,它会因错误 realloc(): invalid next size: 0x0000000000ad92d0 而崩溃。我已经检查了所有内容,但无法理解为什么会出现这种行为。
感谢您的帮助。
数组的定义是:
typedef struct dtab {
unsigned int count;
size_t taille;
void** tab;
} dtab;
这是使用它们的代码:
#include <string.h>
#include "db.h"
int main(int argc, char** argv) {
dtab* db = dtab_create();
char* mot;
unsigned int* pos;
FILE* file = fopen("test/test", "r");
unsigned int i = 0;
mot = malloc(50 * sizeof(char));
pos = malloc(sizeof(unsigned int));
while(fscanf(file, "%s", mot) == 1) {
*pos = ftell(file) - strlen(mot);
dtab_push(db, mot);
dtab_push(db, dtab_create());
dtab_push((dtab*) db->tab[2*i+1], pos);
mot = malloc(50 * sizeof(char));
pos = malloc(sizeof(unsigned int));
i++;
}
print_db(fopen("test/db", "w"), db);
fclose(file);
return 0;
}
文件“测试/测试”包含:
one two
three
而 valgrind 会抛出很多类似的错误:
==24752== Invalid write of size 8
==24752== at 0x400C4E: dtab_push (dtab.c:26)
==24752== by 0x4009E1: main (lookup.c:18)
==24752== Address 0x4c2e4a8 is 6 bytes after a block of size 2 alloc'd
==24752== at 0x4A083AA: realloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==24752== by 0x400BCD: dtab_push (dtab.c:24)
==24752== by 0x4009E1: main (lookup.c:18)
==24752==
==24752== Invalid read of size 8
==24752== at 0x4009FB: main (lookup.c:19)
==24752== Address 0x4c2e4a8 is 6 bytes after a block of size 2 alloc'd
==24752== at 0x4A083AA: realloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==24752== by 0x400BCD: dtab_push (dtab.c:24)
==24752== by 0x4009E1: main (lookup.c:18)
==24752==
【问题讨论】:
-
发布完整代码。例如,知道 t->tab 的类型会很有帮助。
-
t->tab = realloc(t->tab, t->taille);-->>t->tab = realloc(t->tab, t->taille * sizeof *t->tab);BTW:XXX *sizeof (void*)的分配看起来仍然很可疑...... -
@wildplasser 非常感谢。实际上就是这样。我正在使用
void*,因为我需要在同一个数组中存储不同的类型。有没有更好的方法让我的数组通用?也许使用工会? -
恕我直言,最好的方法是将您的结构定义添加到您的帖子中。