I'm currently learning c programming. I've written this code as part of an assignment and keep getting Segmentation faults. Prototypes:
#define ALLOC_ERROR -1
typedef struct monom
{
int coefficient;
int power;
} Monom;
int insertNewMonom(Monom** polynom, int base, int power, unsigned int size);
bool findPlace(Monom** polynom, int power, unsigned int size, int* place);
void printPolyMul(Monom* polynom1, unsigned int polynom1Size, Monom* polynom2, unsigned int polynom2Size);
Here is the relevant code:
void printPolyMul(Monom* polynom1, unsigned int polynom1Size, Monom* polynom2, unsigned int polynom2Size)
{
Monom *mulPolynom = NULL, *temp = NULL;
unsigned int count = 0;
int i, j, size=0, base, power;
for(i=0; i<polynom1Size; i++){
for(j=0; j<polynom2Size; j++){
if(count==size){
size = (size*2)+1;
temp = realloc (sumPolynom, size * sizeof *sumPolynom);
if(!temp){
fprintf(stderr, "Allocation error\n");
exit(ALLOC_ERROR);
}
else
sumPolynom = temp;
}
base = (polynom1[i].coefficient)*(polynom2[j].coefficient);
power = (polynom1[i].power)+(polynom2[j].power);
count += insertNewMonom(&mulPolynom, base, power, count);
}
}
temp = realloc (mulPolynom, count * sizeof *mulPolynom);
if(!temp){
fprintf(stderr, "Allocation Error\n");
exit(ALLOC_ERROR);
}
else
mulPolynom = temp;
printPolynom(mulPolynom, count);
free(mulPolynom);
}
int insertNewMonom(Monom** polynom, int base, int power, unsigned int size)
{
int i, place;
bool new_flag;
Monom tempMonom;
tempMonom.coefficient = base;
tempMonom.power = power;
if(!base)
return 0;
new_flag = findPlace(polynom, power, size, &place);
if(new_flag){
if(place==size){
(*polynom)[place] = tempMonom;
return 1;
}
else{
for(i=size; i>place; i--)
(*polynom)[i] = (*polynom)[i-1];
(*polynom)[place] = tempMonom;
return 1;
}
}
else{
polynom[place]->coefficient += base;
return 0;
}
}
bool findPlace(Monom** polynom, int power, unsigned int size, int* place)
{
int curr;
for(curr=0; curr<size; curr++){
if(polynom[curr]->power==power){
*place = curr;
return false;
}
if(polynom[curr]->power<power){
if(curr)
*place = curr-1;
else
*place = curr;
return true;
}
}
*place = size;
return true;
}
I managed to track down the exact point where the code crashes. It's when bool findPlace(Monom** polynom, int power, unsigned int size, int* place)
is called for the third time, on the second for iteration (curr=1
) when polynom[curr]->power
is being checked.
I'll mention that insertNewPolynom()
was used earlier tin the program for receiving polynom1
and polynom2
and worked just fine.