我写了一个小程序,它使用函数指针做一些数值计算。
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() 错误而崩溃。如果我将函数指针更改为第一个函数 (polynom),它工作正常,但它因 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_end >= 1
调用该函数。
当 l_end == 0
而不是在 p_l[1] = xi;
中有一个越界写操作。
但是请注意,您不能仅仅因为这是您遇到崩溃的地方,或者仅仅因为没有调用此函数就没有崩溃,就推断这是有问题的函数。
错误就是错误,崩溃就是崩溃。它们在 C++ 中是完全不同的;你越早意识到这个重要事实越好。其他地方可能有错误,而这个函数可能只是受害者。
如果您看到崩溃,则表示有错误。如果您没有看到崩溃,您就什么都不知道(错误可能仍然存在)。
关于C++ 代码崩溃并显示 "free(): invalid next size",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8143227/