realloc():下一个大小无效:0x0000000000ad92d0

时间:2014-11-25 00:22:59

标签: c realloc

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

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

文件&#34; test / test&#34;包含:

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

1 个答案:

答案 0 :(得分:0)

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