我正在处理一个现有的c项目(sourceforge上的spglib),我在清理了一些数组初始化后遇到了以下问题:
*检测到glibc * tests / spglibtest:free():下一个大小无效(快):0x08ab46e0 ***
回溯是:
#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
错误发生在下面的“免费(反式)”行中:
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将值分配给trans,如下所示:
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;
}
...
}
在get_translation中写入数组时,Valgrind显示以下内容:
==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)
....
这告诉我,它正在尝试写入已经分配的内存的末尾用于trans,但是它写入trans [0] [0],而trans是维度[2] [3]。这应该有用,AFAIK,任何人都能看到我错过的东西吗?
答案 0 :(得分:6)
您的类型错误,您无法将指针传递给指向数组数组的函数的指针数组(即指向数组的指针)。
对于您拥有的get_translation
签名,您需要:
double (*trans)[3] = malloc(cell->size * sizeof(double[3]));
答案 1 :(得分:2)
所以这可能是一个问题。你的函数似乎假设(基于)trans [num_trans] [j] = someDouble;事实上,trans是一个顺序排列的数组,如上所述,在这种情况下并不是这样。您正在分配一个指针数组而不是二维数组。类似于
的东西double * trans = malloc(cell-&gt; size * 3);可能会更好。通常,您可能希望使用1d数组而不是2d数组,并将其用作2维数组。