I have written a small program which uses function pointers to do some numerical calculations.
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;
}
The program crashes with an unusual free() error. If I change the function pointer to the first function (polynom) it works fine, but it fails with legendre_polynom.
I already debugged that far that it breaks right after exiting that function and before the other code continues.
*** 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]
So my question is what is wrong here?
There is no error in that code, provided that you always call that function with
l_end >= 1.When
l_end == 0instead there is an out of boundary write operation inp_l[1] = xi;.Note however that you cannot infer that this is the function having the problem just because this is where you get a crash or just because not calling this function you have no crash.
An error is an error and a crash is a crash. They are completely distinct in C++; the sooner you realize this important fact the better. There may be an error somewhere else and this function may be just the victim.
If you see a crash then there is an error. If you see no crash you know nothing (the error may be still present).