1

I'm working on a project were I'm supposed to write a program in C where I can add numbers that at up to 500 digits long.

I think I'm close to a working program but I keep getting the message "Segmentation fault" when I run the program.

I have googled this but it seems like you can get this error from alot of different reasons, you just need to figure out which...

I'm not that familiar with C so I thought you guys could maybe help me?

Here is my code so far:

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

// ----------------------------- STRUCTEN --------------------------

typedef struct node *nodeptr;

struct node{
    int data;
    nodeptr next;
};

// ----------------------------- MAIN -------------------------------

int main(){

    // Det krävs 3 listor. En för tal1, en för tal2 och en för svaret.

    nodeptr list1 = NULL;
    nodeptr list2 = NULL;
    nodeptr answer = NULL;

    // Allokerer minnet för listorna.

    list1 = malloc(sizeof(nodeptr));
    list2 = malloc(sizeof(nodeptr));
    answer = malloc(sizeof(nodeptr));

    creat_linked_list(list1, list2, answer);    // Skapar de länkade listorna.

    char first_number[1000];                    // Det första talet får max vara 1000 tecken.

    printf("Enter the first number: ");
    scanf("%s",first_number);

    char second_number[1000];

    printf("Enter the second number: ");
    scanf("%c",second_number);

    int l1 = fill_list(list1, first_number);
    int l2 = fill_list(list2, second_number);

    addition(list1, list2, answer);

return;
}

// ------------------------------ skapa den linkade listan -----------------------------

creat_linked_list (nodeptr list1, nodeptr list2, nodeptr answer){

    // Påbörjar listorna.

    list1 -> next = NULL;
    list2 -> next = NULL;
    answer -> next = NULL;

    list1 -> data = 0;
    list2 -> data = 0;
    answer -> data = 0;


}

// ------------------------------------ Fyller i listorna -----------------------------

int fill_list (nodeptr pointer, char number[]) {

    int x = 0;
    int lenght = strlen(number);

    while (x < lenght){

        int digit = (int)number[x] - (int)'0'; //'0' = 48, tas bort från number[x] för att det är ascii-kodat.
        nodeptr temp = NULL;
        temp = malloc(sizeof(nodeptr));
        temp -> next = pointer -> next;
        pointer -> next = temp;
        temp -> data = digit;
        x = x + 1;

    }
return lenght;
}

// --------------------------------------- Kod för addition av tal -------------------

addition(nodeptr list1, nodeptr list2, nodeptr answer){

    int digit1, digit2;
    int sum, carry;

    while(1){

        if ((list1 -> next != NULL)&&(list2 -> next != NULL)){

            list1 = list1 -> next;  //Tar ut plats i lista 1
            digit1 = list1 -> data; //Tar ut värdet på den platsen.

            list2 = list2 -> next;  // --- || --- 2
            digit2 = list2 -> data; // --- || ---
        }
        else{
            if((list1 -> next = NULL)&&(list2 ->next != NULL)) {

                digit1 = 0; // Eftersom att det inte finns fler siffror i tal 1

                list2 = list2 -> next;  // Samma som IF-satsen innan.
                digit2 = list2 -> data;
            }

            else{

                digit2 = 0; //// Eftersom att det inte finns fler siffror i tal 2

                list1 = list1 -> next;
                digit1 = list1 -> data;
            }
        }
        nodeptr temp = NULL;
        temp = malloc(sizeof(nodeptr));
        temp -> next = NULL;

        temp -> data = (digit1 + digit2 + carry)%10;
        answer -> next = temp;
        answer = answer -> next;

        if ((digit1 + digit2 + carry) > 9) {
            carry = 1;
        }
        else{
            carry = 0;
        }

        if((list1 -> next = NULL)&&(list2 ->next = NULL)) {
            break;
        }

    }

    if (carry){                     // Om det ligger kvar en carry efter att alla tal har blivit adderade
                                    // så går vi in här.
        nodeptr temp = NULL;
        temp = malloc(sizeof(nodeptr));

        answer -> next = temp;
        answer -> data = carry;     
        answer -> next = NULL;      // Markerar slutet av answer listan. 
    }
}

When I run the code I get to the part where I need to enter the first number. After that the code crashes and I get the segmentation fault.

Please Help!

zallke
  • 49
  • 5
  • 1
    Run in a debugger to locate the crash, edit your question to include the relevant code only, including the involved variables and their declarations, initializations and values. – Some programmer dude May 25 '15 at 12:30
  • Just a hint: do you know what `sizeof(nodeptr)` actually is... (spoiler: it'll be 4 or 8), now compare that value to `sizeof(struct node)`... that's why you're getting a segfault – Elias Van Ootegem May 25 '15 at 12:41
  • Ok, I solved it. In the addition function, in the line if((list1 -> next = NULL)&&(list2 ->next = NULL)) I forgot to add an extra "=". it's supposed to be list2 -> next **==** NULL. – zallke May 25 '15 at 13:31

3 Answers3

2

One of your problems, and what's most likely the cause of the crash, is very easy to find:

list1 = malloc(sizeof(nodeptr));
list2 = malloc(sizeof(nodeptr));
answer = malloc(sizeof(nodeptr));

Those malloc calls only allocate the size of nodeptr which is a pointer to the structure, not the structure itself. This will be only four or eight bytes, while your structure is probably eight or twelve bytes big.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Along with other problems, you have

printf("Enter the second number: ");
scanf("%c",second_number);
// -----^

You are reading just 1 char and using second_number as string later. Its not null terminated, so can cause segfault when used as string.

Rohan
  • 52,392
  • 12
  • 90
  • 87
0

500 digits is not support by int, C int only goes from -2^15+1 to +2^15-1

Check this question to know more about C variables range.

Community
  • 1
  • 1
Diogo Cunha
  • 1,194
  • 11
  • 23
  • "where I can add numbers that at up to 500 digits long." are you telling me that C supports 500 digit long numbers for int type? he is missing the dimensions for malloc and it can cut the segmentation-fault when running the program but every number bigger than int range will result in a new segmentation-fault in execution time. – Diogo Cunha May 25 '15 at 12:43
  • "500 digits is not support by int". The OP is trying to do this using home-grown mechanisms, without using "int". Also, there is nothing in the standard to support this claim. There is nothing to support the next claim about the range for "int" either. – cnicutar May 25 '15 at 12:49