【问题标题】:C++ code crashes with "free(): invalid next size"C++ 代码因“free(): invalid next size”而崩溃
【发布时间】: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 中遇到崩溃时,通常意味着内存已损坏。这可能发生在通话之前的任何时间,程序中的任何地方。所以你需要展示一个更完整的例子。

标签: c++ free


【解决方案1】:

该代码没有错误,前提是您始终使用l_end &gt;= 1 调用该函数。

l_end == 0 改为在p_l[1] = xi; 中存在越界写入操作。

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

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

如果您看到崩溃,则说明存在错误。如果您没有看到崩溃,则说明您一无所知(错误可能仍然存在)。

【讨论】:

  • 这成功了。非常感谢。一旦我的限制下降,将批准答案。
猜你喜欢
  • 2013-04-20
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多