【发布时间】:2011-11-15 21:14:30
【问题描述】:
我写了一个小程序,它使用函数指针来做一些数值计算。
double polynom(const int j, const double xi) {
return pow(xi, j);
}
/**
* Calculate the legendre_polynom l_end on a certain position xi.
*/
double legendre_polynom(const int l_end, const double xi) {
vector <double> p_l(l_end+1);
p_l[0] = 1.0;
p_l[1] = xi;
for (int x = 2; x <= l_end; x++) {
// p_l = ((2x-1) * p_{x-1} - (x-1) * p_{x-2}) / l
p_l[x] = ((2 * x - 1) * p_l[x - 1] - (x - 1) * p_l[x - 2]) / x;
}
double result = p_l[l_end];
return result;
}
程序因异常 free() 错误而崩溃。如果我将函数指针更改为第一个函数(多项式),它可以正常工作,但它会因 legendre_polynom 失败。
我已经调试了这么多,它在退出该函数后和其他代码继续之前就中断了。
*** glibc detected *** blub: free(): invalid next size (fast): 0x0804f248 ***
======= Backtrace: ========= /lib/i386-linux-gnu/libc.so.6(+0x6ebc2)[0xb7d70bc2]
/lib/i386-linux-gnu/libc.so.6(+0x6f862)[0xb7d71862]
/lib/i386-linux-gnu/libc.so.6(cfree+0x6d)[0xb7d7494d]
...
number2(_ZN9__gnu_cxx13new_allocatorIdE10deallocateEPdj+0x11)[0x804bc8b]
number2(_ZNSt12_Vector_baseIdSaIdEE13_M_deallocateEPdj+0x25)[0x804bbc3]
number2(_ZNSt12_Vector_baseIdSaIdEED1Ev+0x37)[0x804ba33]
number2(_ZNSt6vectorIdSaIdEED1Ev+0x38)[0x804b8a0]
number2(_Z16legendre_polynomid+0x13f)[0x804af9b]
所以我的问题是这里出了什么问题?
【问题讨论】:
-
您能否提供一个完整的最小示例来演示该问题?
-
另外,
l是最糟糕的变量名! -
也许您应该发布使用函数指针的代码...
-
你试过通过 valgrind 运行它吗?
-
当你在 free() 或 delete 中遇到崩溃时,通常意味着内存已损坏。这可能发生在通话之前的任何时间,程序中的任何地方。所以你需要展示一个更完整的例子。