SIGSEGV PCYCLE...can you tell me whats wrong with this code..thanks..

hi, here’s the code

    #include<stdio.h>

int main(void)
{
    int n,p,j=1,count=0,i,arr1[1010],arr2[2010];
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&arr1[i]);
    }
    for(i=1;i<=n;i++)
    {
        if(arr1[i]!=0)
        {
            count++;
            p=i;
            arr2[j++]=i;
            do
            {
                arr2[j++]=arr1[arr2[j-1]];
                arr1[arr2[j-2]]=0;
            }while(p!=arr2[j-1]);
        }
    }
    printf("%d\n",count);
    for(i=1;i<j;i++)
    {
        printf("%d",arr2[i++]);
        p=arr2[i-1];

        do
        {
            printf(" %d",arr2[i++]);
        }while(p!=arr2[i-1]);
        printf("\n");
        i--;
    }
    return 0;
}

woah common guys …21 views but 0 answers…

the first element in the array arr1 has a garbage value
which during the do while loop is accessed as
arr2[j++]=arr1[“some garbage value”]
which is the reason for the error shown

1 is already assigned to j :slight_smile:

Wild guess : In arr[j-2] j might become negative leading to RTE.

@infinitum j is initialized to 1…by the time you encounter arr[j-2]…j is already 3 so j-2 is a minimum of 1…because after the first time it is used…j only increases…

index 0 of both arr1 and arr2 have garbage value but they are never accessed…the accessing starts from index 1 which is already initialized…

SIGSEGV is mostly caused when you try accessing an invalid array index either a negative index or an index greater then the size of array.The way you have incremented/decremented index might have caused the issue.

I couldnt get the testcase which gives you the error.But here’s my AC soln:

http://www.codechef.com/viewsolution/1654227

Its the same approach but slightly different implementation and gives AC :slight_smile:

could somebody point out the error please…

70 views…0 answers…

do you think value of j would never go above 2010?

i think thats the problem. this could might pass simple testcase but not all and if j goes beyond 2010 it will give SIGSEGV
do
{
arr2[j++]=arr1[arr2[j-1]];
arr1[arr2[j-2]]=0;
}while(p!=arr2[j-1]);

this might make j go beyond 2010 if u can make proper testcases.

//