gpt4 book ai didi

c - 重新分配() : invalid next size: 0x0000000000ad92d0

转载 作者:行者123 更新时间:2023-11-30 19:44:57 24 4
gpt4 key购买 nike

我正在尝试使用动态数组来存储元素,但遇到了一个奇怪的错误。这是定义我的动态数组的代码:

#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;
}

文件“test/test”包含:

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==

最佳答案

您的堆上存在内存损坏。您需要使用某种堆检查工具来运行,例如 valgrind。

关于c - 重新分配() : invalid next size: 0x0000000000ad92d0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27116694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com