- #1
Werg22
- 1,431
- 1
C: Segmentation fault when using free() - Please Help!
This is giving me a big headache. Using free() for some reason results in segmentation faults.
I'm working on making linked structures to represent polynomials modulo a prime p. For the insertion sort below: the consumed pointer (the one passed to sort()) is to be assume to have been allocated on the heap, with a previous call with malloc. I have commented out the statements that lead to errors (basically all calls of free in insert()).
I don't have much time to get this code done, so if anyone can help me out, I'd be very thankful.
This is giving me a big headache. Using free() for some reason results in segmentation faults.
I'm working on making linked structures to represent polynomials modulo a prime p. For the insertion sort below: the consumed pointer (the one passed to sort()) is to be assume to have been allocated on the heap, with a previous call with malloc. I have commented out the statements that lead to errors (basically all calls of free in insert()).
I don't have much time to get this code done, so if anyone can help me out, I'd be very thankful.
Code:
/* definition of linked structure
fields are: coeff for coefficient
expon for exponent
next for pointer to next term structure or NUL */
struct term {
int coeff ;
int expon ;
struct term *next ;
};
/* implementation of insertion sort for term structures */ struct term *insert(struct term *a, struct term *b, int p)
{
struct term *temp = malloc(sizeof(struct term));
a->coeff = addp(a->coeff, 0, p);
if (a->coeff == 0) {
/* free(a) ************ ERROR ************** */
return b;
}
if (b == NULL) {
a->next = NULL;
return a;
}
if (a->expon == b->expon) {
if (addp(a->coeff, b->coeff, p) == 0) {
temp = b->next;
/*free (a);
free (b); ************ ERROR ************** */
return temp;
}
b->coeff = addp(a->coeff, b->coeff, p);
/*free(a); ************ ERROR ************** */
return b;
}
if (a->expon < b->expon) {
a->next = b;
return a;
}
temp = b->next;
b->next = insert(a, temp, p);
return b;
}
struct term *sort (struct term *pterms, int p)
{
struct term *temp;
if (pterms == NULL) return NULL;
temp = pterms->next;
return insert(pterms, sort(temp, p),p);
}
Last edited: