*** glibc detected *** free(): invalid next size (fast) — should work?

32 篇文章 0 订阅

问:

I'm working on an existing c project (spglib on sourceforge), and I'm running into the following problem after cleaning up some array initializations:

* glibc detected tests/spglibtest: free(): invalid next size (fast): 0x08ab46e0 **

The backtrace is:

#0  0xb7fe1424 in __kernel_vsyscall ()
#1  0xb5cfdd61 in raise () from /lib/libc.so.6
#2  0xb5cff5ee in abort () from /lib/libc.so.6
#3  0xb5d397ed in ?? () from /lib/libc.so.6
#4  0xb5d3f7b1 in ?? () from /lib/libc.so.6
#5  0xb5d4052b in ?? () from /lib/libc.so.6
#6  0xb5d441cd in free () from /lib/libc.so.6
#7  0xb6681484 in sym_get_multiplicity (cell=0xbfffe1f0, symprec=0.050000000000000003) at /git/xtalopt-public/src/spglib/symmetry.c:168
#8  0xb6680550 in spg_find_primitive (lattice=0xbfffe2a8, position=0x813c6f0, types=0x813c700, num_atom=2, symprec=0.050000000000000003)
    at /git/xtalopt-public/src/spglib/spglib.c:253

The error is in the "free(trans)" line below:

int sym_get_multiplicity(const Cell *cell, const double symprec)
{
  int i, rc;
  double **trans;
  trans = (double**)malloc(cell->size * sizeof(double*));
  for (i = 0; i < cell->size; i++) {
    trans[i] = (double*)malloc(3 * sizeof(double));
  }

  rc = get_translation(&trans[0][0], identity, cell, symprec);

  for (i = 0; i < cell->size; i++) {
    free(trans[i]);
  }
  free(trans);

  return rc;
}

get_translation assigns values to trans like so:

static int get_translation(double trans[][3], const int rot[3][3], const Cell *cell,
                           const double symprec)
{
...
  for (j = 0; j < 3; j++) {
    trans[num_trans][j] = someDouble;
  }
...
}

Valgrind is showing the following when writing to the array in get_translation:

==17929== Invalid write of size 8
==17929==    at 0x56BE8A7: get_translation (symmetry.c:285)
==17929==    by 0x56BE44B: sym_get_multiplicity (symmetry.c:163)
...
==17929==  Address 0x9cb5868 is 0 bytes after a block of size 8 alloc'd
==17929==    at 0x4024918: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==17929==    by 0x56BE3F7: sym_get_multiplicity (symmetry.c:158)
....

This suggests to me that it's trying to write past the end of the allocated memory for trans, but it's writing to trans[0][0], and trans is of dimension [2][3]. This should work, AFAIK, can anyone see something that I'm missing?


回答:


Your types are wrong, you can't pass a pointer to an array of pointers to a function expecting an array of arrays (i.e. a pointer to an array).

For the signature of get_translation that you have, you need:

double (*trans)[3] = malloc(cell->size * sizeof(double[3]));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值