Why am I getting SIGABRT error? (PSHOT)

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

int winner(char s, int n)
{
int a=0,b=0;
int c=0;
while(c!=strlen(s))
{
if(c%2==0)
{
if(s[c]==‘1’)
a++;
if(b>((2
n)-c)/2 -1)
break;
}
else
{
if(s[c]==‘1’)
b++;
if(a>((2*n)-(c-1))/2 -1)
break;
}

    c++;
}
if(s[c]=='\0')
    return c;

return c+1;

}

int main()
{
int t,n;
char *s;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
scanf("%d",&n);
s=(char )malloc(2n * sizeof(char));
scanf("%s",s);

 printf("%d\n",winner(s,n));
 free(s);

}
return 0;

}

Format your code man

1 Like

This code is running perfectly on my local pc. Don’t really understand why it is showing a runtime error in here

Format your code.
Use ``` at the start and end of code
Send the question link

What is that used for?

So that your code is easy to read

This is the question link

I did not get you! Are you suggesting me to add comments?

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

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

int winner(char *s, int n)
{
    int a=0,b=0;
    int c=0;
    while(c!=strlen(s))
    {
        if(c%2==0)
        {
            if(s[c]=='1')
            a++;
            if(b>((2*n)-c)/2 -1)
                break;
        }
        else
        {
            if(s[c]=='1')
                b++;
             if(a>((2*n)-(c-1))/2 -1)
                break;
        }

        c++;
    }
    if(s[c]=='\0')
        return c;

    return c+1;
}



int main()
{
 int t,n;
 char *s;
 scanf("%d",&t);
 for(int i=1;i<=t;i++)
 {   
     scanf("%d",&n);
     s=(char *)malloc(2*n * sizeof(char));
     scanf("%s",s);

     printf("%d\n",winner(s,n));
     free(s);
 }
 return 0;

}
1 Like

I did format the code!.

here is the link to my submission.
https://www.codechef.com/viewsolution/33064499

1 Like

The problem that immediately jumps out is that you aren’t allocating enough memory for s: it must contain all 2 * n characters it reads in, plus the null-terminator character.

3 Likes

Yeah you always need to allocate size+1. But I would suggest to use string

Thanks!

1 Like