PALIN: getting Runtime error

#include<stdio.h>
#include<string.h>
int copystring(char *a,long int mid1,long int mid2);
int start(char *a);
int check(char *a,long int mid1,long int mid2)
{
if(mid1<0)
return 1;
if(a[mid1]<a[mid2])
{
a[mid2]=a[mid1];
return 1;
}
if(a[mid1]>a[mid2])
return 0;
else return check(a,mid1-1,mid2+1);
}

int increment(char *a,long int pos)
{
	if(pos<0)
		return 0;
	if(a[pos]!='9')
	{
		a[pos]++;
		return 0;
	}
	if(pos==0)
	{
		long int i;
		long int len = strlen(a);
		for(i=1;i<=len;i++)
		{
			a[i]='0';
		}
		a[0]='1';
		a[len]='1';
		a[len+1]='\0';
		return 1;
	}
	a[pos]='0';
	return increment(a,pos-1);
}

int match(char *a,long int mid1,long int mid2)
{
	int flag=0;
	if(mid1<0)
		return 0;	
	if(a[mid1]==a[mid2])
	{
		if(check(a,mid1-1,mid2+1))
		{
			flag=increment(a,mid1);
			if(flag==1)
			{
				return 0;
			}
			a[mid2]=a[mid1];
			copystring(a,mid1,mid2);
			return 0;
		}
		match(a,mid1-1,mid2+1);
		return 0;
	}
	if(a[mid1]>a[mid2])
	{	
		a[mid2]=a[mid1];
		copystring(a,mid1-1,mid2+1);
		return 0;
	}
	else
	{
		increment(a,mid1);
		a[mid2]=a[mid1];
		copystring(a,mid1,mid2);
		return 0;
	}
}

int copystring(char *a,long int mid1,long int mid2)
{
	if(mid1<0)
		return 0;
	a[mid2]=a[mid1];
	copystring(a,mid1-1,mid2+1);
	return 0;
}


int start(char *a)
{
	long int len;
	len=strlen(a);
	long int mid1 = len /(long int) 2,mid2;
	mid2=mid1;
	if(len%2 == 0)
		mid1--;			
	match(a,mid1,mid2);
	return 0;
}

int main()
{
	int t;
	scanf("%d",&t);
	char a[1000002];
	while(t--)
	{
		
		scanf("%s",a);
		start(a);
		printf("%s",a);	
		if(t) printf("\n");
	}
	return 0;
}

It seems that my code generates a segmentation fault in some way... Can you please tell me for what case the error occurs?

segmentation fault occurs when the hardware notifies an operating system about a memory access violation.

i think there is a problem in ur all function for example

int check(char *a,long int mid1,long int mid2)

{

if(mid1<0)

     return 1;

 if(a[mid1]<a[mid2])

{

    a[mid2]=a[mid1];

    return 1;

}

if(a[mid1]>a[mid2])

    return 0;

else return check(a,mid1-1,mid2+1);

}

in this function there is a condition when mid1 become negative then function return 1 but in recursive call u r incrementing the value of mid2 by 1 but there is no condition in ur function to check the mid2 is with in boundary or not .

so add in first if statement in functions:

if(mid1<0||mid2>=strlen(a))

return 1;

and i checked ur code and submitted with the changes i have said to u no segme
ntation fault is encountered but as ur algo is not good enough to get AC so There will BE TLE signal for ur solution :slight_smile:

for better algo than this you can read Given a number, find the next smallest palindrome - GeeksforGeeks

WARNING :: dont copy that code :stuck_out_tongue:

here is modified code CodeChef: Practical coding for everyone

3 Likes