bullseye
bullseye

Reputation: 81

SIGSEV error on SPOJ, though code works fine on ideone

        #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef ONLINE_JUDGE
// no getchar_unlocked on Windows so just call getchar
#define gc getchar
#else
#define gc getchar_unlocked
#endif



void multiply(char answer[], char a[], char b[])
{
int la = strlen(a);
int lb = strlen(b);
char c[la+lb+3];

int i,j,k,x;
char temp = '0' -  48;

for(i=0;i<la;i++)
    a[i] = a[i] - 48;
for(i=0;i<lb;i++)
    b[i] = b[i] - 48;



for(i=0;i<la+lb+2;i++){
    c[i] = '0' - 48;


}




for(i=lb-1,x=la+lb+1;i>=0;i--)
{
    temp = '0' - 48;
    k= x;
    for(j=la-1;j>=0;j--)
    {
        int temp1 = (c[k]+ temp + a[j]*b[i]);
        c[k] = (int)temp1%10;
        temp = (int)temp1/10;
        k--;
    }
    c[k] = temp;
    x--;

}
for(i=0;i<la;i++)
{
    a[i] = a[i]+48;
}

for(j=0;j<lb;j++){
    b[j] = b[j]+48;
}


while(c[k] == '0'-48)
    k++;

int p =0;
for(i=k;i<la+lb+2;i++){
    answer[p] = c[i] + 48;

    p++;
}
answer[p] = '\0';


}


int main(void)
{
#ifndef ONLINE_JUDGE
 freopen ("/home/gautam/Dropbox/Programming/SPOJ/input.txt", "r", stdin);
 #endif // ONLINE_JUDGE
long int t;
scanf("%ld",&t);
while(t>0){
char a[1002];
char b[1002];
scanf("%s", a);
scanf("%s", b);
if(strlen(a) == 1 && a[0] == '0' || strlen(b) == 1 && b[0] == '0')
    printf("0\n");
else{

char *answer;
int la = strlen(a);
int lb = strlen(b);
answer= (char *)malloc(sizeof(char)*(la+lb+3));

multiply(answer,a,b);

printf("%s\n", answer);
   }
 t--;
}
   return 0;    



 }

The problem is to multiply large numbers with atmost 1000 digits each, here's the link:Problem. I have taken input in strings and have used arrays to multiply. I have tried it on ideone which works absolutely fine, but on SPOJ it gives SIGSEV error. Please help.

Upvotes: 1

Views: 150

Answers (1)

Sergii Dymchenko
Sergii Dymchenko

Reputation: 7209

Your char arrays a and b can hold only up to 1002 digits, while the problem statement says "at most 10000 decimal digits each".

Upvotes: 1

Related Questions