C++代码崩溃并显示"free(): invalid next size"

C++ code crashes with "free(): invalid next size"

本文关键字:invalid size next free 代码 崩溃 显示 C++      更新时间:2023-10-16

我写了一个小程序,它使用函数指针进行一些数值计算。

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调用该函数,则该代码中没有错误。

当CCD_ 2替代地在CCD_ 3中存在边界外写入操作时。

然而,请注意,不能仅仅因为这是发生崩溃的地方,或者仅仅因为不调用该函数就没有崩溃,就推断出这是有问题的函数。

错误就是错误,崩溃就是崩溃。它们在C++中是完全不同的;你越早意识到这一重要事实越好。其他地方可能存在错误,而此函数可能只是受害者。

如果您看到崩溃,则说明存在错误。如果你没有看到崩溃,你什么都不知道(错误可能仍然存在(。