Crash while writing or reading from memory

Last Edited By Krjb Donovan
Last Updated: Mar 11, 2014 07:51 PM GMT

Question

Hello Zlatko; [j0][k0][h0];. I think this problem causes while writing or reading from memory in this function. Can you help to find the reason of the crash?

int* chseq_r(int seq[n][kl][hl]) { int* result=new int[n*kl*hl]; int j0,k0,h0,j1,k1,h1, l0,l1, r,sum_ope=0; float ls,nr;

for (j=0;j<n;j++){ sum_ope+=(kj[j]*hj[j]); }

choose_l0:

ls=0; nr=(1000/sum_ope); r=rand()%1000; for(j=0;j<n;j++) for(k=0;k<kj[j];k++) for(h=0;h<hj[j];h++){ if(ls<r){

        	j0=j;
           k0=k;
           h0=h;
        }
        ls+=nr;
     }                          

l0=seq[j0][k0][h0];

if(l0==1) goto choose_l0;


for(j=0;j<n;j++) for(k=0;k<kj[j];k++) for(h=0;h<hj[j];h++){

        	if(seq[j][k][h]==l0-1){
           	j1=j;
              k1=k;
              h1=h;
              l1=seq[j][k][h];
              cout<<"              j1,k1,h1= "<<j1<<k1<<h1;
              if((j1==j0 && k1==k0)||(j1==j0 && h1==h0))
               	goto choose_l0;
              else{
                 seq[j0][k0][h0]=l1;
                 seq[j1][k1][h1]=l0;
                 goto end;
              }}}

end:

for(j=0;j<n;j++) for(k=0;k<kl;k++)

  	for(h=0;h<hl;h++){
     	q=(j*kl*hl)+(k*hl)+h;
        result[q]=seq[j][k][h];
     }

return result; }

Answer

Hello Amir

When the function enters, the j0, k0, and h0 are uninitialized. It means they take on unpredictable values. The first time through, ls is 0, and it is possible that r=rand()%1000; produces 0. Then (ls < 0) will be false and j0 and k0 and h0 will not be initialized. Here is the code I'm referring to.

   ls=0;
   nr=(1000/sum_ope);
   r=rand()%1000;
   for(j=0;j<n;j++)
       for(k=0;k<kj[j];k++)
           for(h=0;h<hj[j];h++){
               if(ls<r){
                   j0=j;
                   k0=k;
                   h0=h;
               }
               ls+=nr;
           }
           l0=seq[j0][k0][h0];

The last line shows j0,h0,k0 being used to access an array. That is one source of trouble.

Initialize all your local variables in all your functions. Instead of this: int j0,k0,h0,j1,k1,h1, l0,l1, r,sum_ope=0; do this: int j0 = 0, k0 = 0, h0 = 0, j1 = 0, k1 = 0, h1 = 0, l0 = 0, l1 = 0, r = 0, sum_ope=0;

The initial values may not be correct for your calculations, but at least they will be initialized to a predictable value.

Advertisement

©2017 eLuminary LLC. All rights reserved.