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

标签 c++ free

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

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/

相关文章:

c++ - 制作控制台进度条? ( Windows )

c++ - 在 native C++ 中以编程方式连接到 OpenVPN

分配内存时代码导致段错误或释放内存时中止程序

c - 这个错误在 C : free(): invalid next size (fast): 0x00000000020b0200 中意味着什么

c++ - 指向数组删除的指针

c++ - 编译器可以用直接初始化代替复制初始化吗?

c++ - "for(;;)"比 "while (true)"快吗?如果不是,人们为什么要使用它?

c++ - 如何将 CString 转换为字节

c - mallinfo 在嵌入式系统中的使用

c - 如何避免在每个 "return "之前调用 free()