Sigabrt error in c programing

1.7k Views Asked by At

plz help me to remove SIBABRT error for the following code,plz suggest me why this error occurs even after getting correct output

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

int main()
{
char x[25],y[25];
int i,j=0;
scanf("%s",x);
for(i=0;i<strlen(x);i++)
{
    if(x[i]>=97 && x[i]<=122)
    {
        y[j]=x[i]-32;
        j++;
    }
    else if(x[i]>=65 && x[i]<=90)
    {
        y[j]=x[i]+32;
        j++;
    }

}
printf("%s",y);}
2

There are 2 best solutions below

0
On

If the input is less than 25 characters, then the string will be null terminated. If the size exceeds the array size specified then it overwrites the memory not belonging to the array.

So fgets() is the alternative for scanf() in such case.

0
On

Think of the difference between the source and the destination array, something is missing in the destination. The null-terminator.

Note: Both the arrays are local variable with automatic storage and unless initialized explicitly, their content is indeterminate.

Without a null-terminator in place, printf() will go out of bound for the supplied array while printing with %s which invokes undefined behavior.

The easiest way to handle this is zero-initilize the arrays, like

  char x[25] = {0} ,y[25] = {0};

which makes all the elements of the arrays set to 0, and the same value being used as null-terminator, you are not required to add one manually to the destination array.

Also, FWIW,

  • You should length-limit the input to prevent buffer overflow from longer than expected input, using something along the line scanf("%24s",x);

  • better to use fgets() to take the user input. If, iff, you have to use scanf(),you can use it but please use proper error checking.