-1

My Code

int i,v,o,p,j;
v=0;
o=0;
char x[12]={'#','v','v','o','#','o','v','#','v','o','o','#'};
void vukovi (char a[])
{
    for (i=0;i<12;i++){
        if (x[i]=='#'){
            for (j=i+1;x[j]!='#';j++){
                if (x[j]=='v'){
                    v=v+1;
                }
                if (x[j]=='o')
                    o=o+1;
            }

            if (v>=o){
                for (j=i+1;x[j]!='#';j++){
                    if (x[j]=='o'){
                        x[j]='.';
                    }
                }
            }

        }
        v=0;
        o=0;
    }

for (i=0;i<12;i++){
    printf("%c",x[i]);
    }
}
vukovi(x);
return 0;}

Sometimes it prints well.
Sometimes error

.exe stopped working

I have no idea why.
Idea of program is : everywhere between two # where is v>o , o must be replaced with .
Like I said when it prints, it prints well.
Otherwise error. Help ?
( I Have left out include and main function ).

Suraj Jain
  • 4,267
  • 25
  • 39
domdrag
  • 405
  • 3
  • 11

2 Answers2

5

when i==11 this loop is wrong:

for (j=i+1;x[j]!='#';j++){

since it makes j start at 12. You are already outside the string, but advance forward in the woods since your loop stops on #: undefined behaviour.

It stops if you encounter a # char while going through unallocated memory (can happen or not) or when you encounter a page boundary beyond what the system detects an illegal read and stops with SEGV.

Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
0

What You Are Facing is Segmentation Fault.
You are accessing memory which you are not supposed to.

This Part Of Your Code:

for (i=0;i<12;i++){          //Till i<12, that means when i = 11 loop will run.
        if (x[i]=='#'){
            for (j=i+1;x[j]!='#';j++){  //j =  i+1, for i = 11, j = 12
                if (x[j]=='v'){         
                    v=v+1;
                }
                if (x[j]=='o')
                    o=o+1;
            }

            if (v>=o){
             for (j=i+1;x[j]!='#';j++){  //j =  i+1, for i = 11, j = 12
               if (x[j]=='o'){         //x[j] , for j = 12 , x[12]
                x[j]='.';  //x[12] = '.' You Are Accessing Memory You Are Not Supposed to.
                    }
                }
            }

You should not access array out of bound, it has many risks.
Please See This Question How dangerous is it to access an array out of bounds?, I highly recommend it.

Community
  • 1
  • 1
Suraj Jain
  • 4,267
  • 25
  • 39