The Next Pallindrome(SIGSEGV error)

This code is running perfectly on my computer and giving the correct answer for all test cases,but don’t know why it is giving runtime error(SIGSEGV) while running on the online judges.
Tried everything but unable to figure out the reason.

#include<stdio.h>
#include<string.h>

int main()
{
int i,j,t,n;
char num[10];
scanf("%d",&t);
while(t–)
{
scanf("%s",num);
n=strlen(num);
num[n-1]=num[n-1]+1;
if(n%2==0)
{
for(i=0,j=n-1;i<(n/2)-1;i++,j–)
num[j]=num[i];
if(num[i]<num[j])
{
num[i]=num[i]+1;
num[j]=num[i];
}
else num[j]=num[i];
}
else
{
if(num[n/2]<num[n/2+1]&&num[n/2-1]<num[n/2+1])
num[n/2]=num[n/2]+1;

            for(i=0,j=n-1;i<(n/2);i++,j--)
               num[j]=num[i];

    }
    printf("%s",num);
    printf("\n");
}
return 0;

}

Code with increased readability:

#include<stdio.h>

#include<string.h>

int main()
{

int i,j,t,n;

char num[10];
scanf("%d",&t);
while(t--)
{
    scanf("%s",num);
    n=strlen(num);
num[n-1]=num[n-1]+1;
    if(n%2==0)
    {
        for(i=0,j=n-1;i<(n/2)-1;i++,j--)
            num[j]=num[i];
        if(num[i]<num[j])
        {
            num[i]=num[i]+1;
            num[j]=num[i];
        }
        else num[j]=num[i];
    }
    else
    {
        if(num[n/2]<num[n/2+1]&&num[n/2-1]<num[n/2+1])
            num[n/2]=num[n/2]+1;

            for(i=0,j=n-1;i<(n/2);i++,j--)
               num[j]=num[i];

    }
    printf("%s",num);
    printf("\n");
}
return 0;

}

The SIGSEGV error is because of the statement

char num[10]; // should be char num[1000005];

This is because the input number can have upto 1000000 digits so you need a larger array.

Also num[n-1]=num[n-1]+1; won’t work for all cases. If the input string is 5299 you need to take care of the carry, ie the carry would we added to the next number. Also if the input string is something like 9999 then after carrying the size of array would increase by 1, ie the new number would be 10000. To resolve this you could simply calculate the number of 9’s in input string. If count(9)==strlen(num) then the new num will be 1 followed by count(9) times 0. If count(9)!=strlen(num) and if the last digit is 9 you have to keep on carrying until a digit less than 9 is reached.

AC :slight_smile:
Thanks michelangelo.