【问题标题】:Why does compiler throw "terminate called recursively"为什么编译器会抛出“递归调用终止”
【发布时间】:2021-10-28 12:26:24
【问题描述】:

我正在尝试使用 C++ 将二维数组传递给函数。作为其中的一部分,当我将空间分配给 3*2 矩阵时,在执行过程中,我无法弄清楚为什么编译器会抛出“终止调用递归”。

任何帮助将不胜感激。

编辑:这在在线编译器中工作得很好。 (我的系统使用了 gcc 编译器 -> Windows 上的 MingW)

void printMat(int **arr, int m, int n)
{
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            cout<<arr[i][j]<<" ";
}

int main()
{
    int m=3, n=2;

    int **arr;
    arr = new int *[m];

    for(int i=0; i<m; i++)
    {
        arr[i] = new int[n];
        for(int j=0; j<m; j++)
        {
            arr[i][j]=i;
            cout<<arr[i][j]<<" ";
        }
    }
    cout<<"Reached"<<endl;
    printMat(arr, m, n);
    return 0;
}

【问题讨论】:

  • 首先请注意,您的错误不会发生在编译器中,而是发生在您的程序中。至于问题,你的程序崩溃了。然后在退出时再次崩溃。使用 调试器 查找崩溃的位置。
  • main() 中的内部循环具有未定义的行为,因为结束条件是j &lt; m 而不是j &lt; n。因此它会修改每个arr[i]n 元素末尾之后的元素

标签: c++ pointers c++14


【解决方案1】:

我强烈建议在所有调试版本中使用清理程序来跟踪这些错误,请参阅live example,它可以快速告诉您问题所在。

=================================================================
==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018 at pc 0x000000401752 bp 0x7ffeb62d0c60 sp 0x7ffeb62d0c58
WRITE of size 4 at 0x602000000018 thread T0
    #0 0x401751 in main /app/example.cpp:22
    #1 0x7f48243620b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #2 0x4011dd in _start (/app/output.s+0x4011dd)

0x602000000018 is located 0 bytes to the right of 8-byte region [0x602000000010,0x602000000018)
allocated by thread T0 here:
    #0 0x7f48252cf0b7 in operator new[](unsigned long) (/opt/compiler-explorer/gcc-11.2.0/lib64/libasan.so.6+0xb30b7)
    #1 0x4015db in main /app/example.cpp:19
    #2 0x7f48243620b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)

SUMMARY: AddressSanitizer: heap-buffer-overflow /app/example.cpp:22 in main

意思是arr[i][j]=i;会导致缓冲区溢出,因为循环for(int j=0; j&lt;m; j++)中的mn错字。

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多