blasanka blasanka - 1 year ago 121
C++ Question

How to fix stack smashing detected in array using loop

When I try to compile the below c++ code in ubuntu 14.04 terminal it says stack smashing detected abc2 terminated Aborted (core dumped). How I can avoid this? thanks for advance.

#include <iostream>

using namespace std;

void displayArray(int arr[][4],int row,int col);
int main(){
int arr[3][4];
for(int i=0;i<4;i++){
cout<<"enter value ";
cin>>arr[0][i];
for(int r=0;r<3;r++){
arr[i+1][r]=0;
}
}



displayArray(arr,3,4);

return 0;
}

void displayArray(int arr[][4],int row,int col){
for(int i=0;i<row;i++){
for(int r=0;r<col;r++){
cout<<arr[i][r]<<" ";
}cout<<endl;
}

}

Answer Source

You are going beyond the bounds of your array here:

int arr[3][4];
for(int i=0;i<4;i++){
 //...
   arr[i+1][r]=0; // <-- i+1 when i == 2 is going to give trouble
//...
}

If i >= 2, you're writing to arr[3], arr[4], etc. This is a memory overwrite and the behavior then becomes undefined.

Obviously the fix is either to throttle the loop back so that i is always less than 2, or your array's first dimension needs to be increased from 2 to a bigger number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download