Alireza Hashemi Alireza Hashemi - 3 days ago 6
C++ Question

*** stack smashing detected *** in a C++ array program

I'm writing a simple program which simulates a real world physics problem about electron spin.
It should fill an array of 10 with 1 or -1 randomly. then for 100 times choose one element and do the following conversion based on it's neighbors:

+-+ ..... +++
-+- ..... ---
+++ ..... +++
--- ..... ---


and in the following cases randomly pick a result:

-++ ..... --+ or -++
--+ ..... --+ or -++
+-- ..... ++- or +--


etc

but when i run it i get this error:
* stack smashing detected *: ./a.out terminated
Aborted (core dumped)

I checked and it's on the last "else" two lines. it doesn't give error when i comment them.

My code:

#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main(){
srand(time(NULL));
int arr[10],a[2],i,curr,next,prev,j;
double r;
//Fill arr[10] with random -1 & 1
a[0]=-1; a[1]=1;
for(i=0;i<10;i++){
r=rand()/(RAND_MAX+1.0)*2.0;
arr[i]=a[int(r)];
}
//Cout arr[10]
for(i=0;i<10;i++)cout<<arr[i]<<" ";
cout<<'\n';
//Repeat for 100 times
for(j=1;j<=100;j++){
r=rand()/(RAND_MAX+1.0);
r=(r)*11;
curr=int(r);
next=(curr+1)%11;
prev=(10+curr)%11;
if(arr[prev]==arr[next]){
if(arr[prev]==1)arr[curr]=1; else arr[curr]=-1;
}
else
{
r=rand()/(RAND_MAX+1.0)*2.0;
arr[curr]=a[int(r)];
}
}
//Cout arr[10]
for(i=0;i<10;i++)cout<<arr[i]<<" ";
cout<<'\n';
return 0;
}


Thanks in advance.

Answer
    r=(r)*11;
    curr=int(r);
    //...
    arr[curr]=//...

r can take a value of 10.X at low probability, causing curr to take the value of 10, assigning to arr at 10, which corrupts memory.

Comments