-
Sigesgv error
CAN ANYONE TELL ME AS TO WHY AM I GETTING SIGSEGV ERROR WHILE SUBMITTING THIS CODE
Code:
- #include<stdio.h>
- #include<math.h>
- #include<stdlib.h>
- #include<string.h>
- #define MAX 10000
-
- char * multiply(char [],char[]);
- int main()
- {
- int t;
- scanf("%d",&t);
- while(t--)
- {
- char a[MAX];
- char b[MAX];
- char *c;
- int la,lb;
- int i;
- scanf("%s",a);
- scanf("%s",b);
- c = multiply(a,b);
- int sum=0;
- for(int q=0;c[q]!='\0';q++)
- sum=sum+c[q];
- sum=sum%3;
- printf("%d\n",sum);
- }
- return 0;
- }
-
- char * multiply(char a[],char b[]){
- static char mul[MAX];
- char c[MAX];
- char temp[MAX];
- int la,lb;
- int i,j,k=0,x=0,y;
- long int r=0;
- long sum = 0;
- la=strlen(a)-1;
- lb=strlen(b)-1;
- for(i=0;i<=la;i++){
- a[i] = a[i] - 48;
- }
-
- for(i=0;i<=lb;i++){
- b[i] = b[i] - 48;
- }
-
- for(i=lb;i>=0;i--){
- r=0;
- for(j=la;j>=0;j--){
- temp[k++] = (b[i]*a[j] + r)%10;
- r = (b[i]*a[j]+r)/10;
- }
- temp[k++] = r;
- x++;
- for(y = 0;y<x;y++){
- temp[k++] = 0;
- }
- }
- k=0;
- r=0;
- for(i=0;i<la+lb+2;i++){
- sum =0;
- y=0;
- for(j=1;j<=lb+1;j++){
- if(i <= la+j){
- sum = sum + temp[y+i];
- }
- y += j + la + 1;
- }
- c[k++] = (sum+r) %10;
- r = (sum+r)/10;
- }
- c[k] = r;
- j=0;
- for(i=k-1;i>=0;i--){
- mul[j++]=c[i] + 48;
- }
- mul[j]='\0';
- return mul;
- }
-
Is there a reason you're using strings instead of numbers for your input?
Without any prompts for the data entry you're asking for problems and the lack of meaningful variable names makes following the logic difficult if not impossible.
By the way the program seems to run without crashing for me, be careful with those greater than and equal operations in your for loops remember that arrays stop at size - 1.
-
What's your input?
What do you mean by 'submit'?
Are you using some online programming contest / auto verification tool?
> int t;
> scanf("%d",&t);
One which provides 'n' example tests on stdin?
> y += j + la + 1;
It seems to me you're adding la a lot of times.
Are you sure y stays in-bounds?
Also, lay off the all-caps.
How To Ask Questions The Smart Way
-
If your inputs can be 10000 digits long and you're reading them as a string, you need 10001 chars to be able to hold the terminating '\0'.
Multiplying two 10000 digit numbers can give a 20000 digit answer. So mul in multiply should be MAX*2+1 (at least).
However, since you ultimately want the mod 3 of the result it's a waste of time multiplying the two large numbers. Just calculate the mod 3 of each of them (by adding their digits (sum of a[i]-'0')) and taking the mod 3 of that), multiply those together, and then take the mod 3 of that.