Not Sure where functions are segfaulting.

For an assignment I have to code up 6 functions that each do a different task. In two of my functions, I am seg faulting and I don't know why. I feel like the solutions are obvious, but I just can't see them. I'm still a beginner when it comes to programming. Here are the two functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
HugeInteger *parseInt(unsigned int n)
{
    int i, number=n;
    int count=0;
    HugeInteger *ptr=malloc(sizeof(HugeInteger));
    if(ptr==NULL)
        return NULL;
    while (number != 0) {
        number=number/10;
        count++;
    }

    //printf("crash");
    ptr->digits=malloc(sizeof(int)*count);
    if(ptr->digits==NULL)
        return NULL;
    //printf("crash");


    for(i=0; i < count; i++){
       ptr->digits[i]=number%10;
       number=number/10;
    }
    //printf("crash");
    //hugeDestroyer(ptr);
    return ptr;

}

unsigned int *toUnsignedInt(HugeInteger *p)
{
    int i;
    //printf("crash");
    int *sum;
    unsigned int *ptr=malloc(sizeof(unsigned int));
    HugeInteger *q;

    if(ptr==NULL)
        return NULL;
    if (p==NULL)
        return NULL;
    for(i = 0; i < p->length; i++)
        *sum += p->digits[i] * pow(10, i);
    q = parseInt(*sum);

    if(p->length != q->length)
        return NULL;

    for(i = 0; i < p->length; i++){
        if(p->digits[i] != q->digits[i])
            return NULL;
    }
    hugeDestroyer(q);
    return sum;
}

Is this supposed to be C or C++? (Looks like C to me, so I'll let the malloc/printf thing slide.)

Just a shot in the dark here, but is it perhaps because you're not setting ptr->length in parseInt?
I don't see the cause in parseInt on casual inspection, although long double main's observation is certainly likely. There a couple other bugs in parseInt. If the condition on line 15 evaluates to true, ptr needs to be freed or you will be leaking memory.

Also, according to the loop condition on line 8 in parseInt, number will be 0 when the loop that begins on line 20 is reached. If number is 0, what is the result of that loop?

In toUnsignedInt you never point sum anywhere, but treat it as if you did. Are you sure you should be returning a pointer here? If the condition on line 45 evaluates to true, you must free ptr and q or you will leak memory. If the condition on line 50 evaluates to true, you must free ptr and q or you will leak memory.
Last edited on
It's C. I set ptr->length to 0 and it 's no longer crashing.
Topic archived. No new replies allowed.