Reputation: 89
I'm trying to experiment passing 2D arrays to a function using C++. As part of that, when I allocated the space to a 3*2 matrix, and during execution, I'm not able to figure out as to why the compiler throws "terminate called recusively".
Any help would be appreciated.
Edit: This works perfectly fine in Online compiler. (My system used a gcc compiler -> MingW on Windows)
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;
}
Upvotes: 3
Views: 599
Reputation: 19213
I strongly recommend using sanitizers in all debug builds to track these bugs, see live example that quickly tells you what is wrong.
=================================================================
==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
Meaning the arr[i][j]=i;
causes causes buffer overflow because of a m
<->n
typo in the loop for(int j=0; j<m; j++)
.
Upvotes: 1