我正在尝试用 C 创建一个多项式乘法程序,其中我实现了一个名为
pmult
的函数,用于两个多项式的乘法。该程序运行良好,直到需要为相同的指数值添加多项式。在这个阶段,我遇到了分段错误,并显示错误消息:
malloc(): corrupted top size
我该怎么办?
Example i used:
p1:
No. of elements=5
coeff expo
2 6
5 3
3 2
2 1
3 0
Example i used:
p2:
No. of elements=5
coeff expo
3 7
2 6
5 4
3 2
7 0
这是源代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct poly{
int coeff;
int expo;
} poly;
poly *pmult(poly *p1, poly *p2, int term1, int term2, int term, int *ptr);
poly *create(int term);
void display(poly *p, int term);
poly *create(int term)
{
poly *p = malloc(term * sizeof(poly));
for (int i = 0; i < term; i++)
{
printf("Enter the coefficient and the exponent of the polynomial:");
scanf("%d%d", &p[i].coeff, &p[i].expo);
}
return p;
}
poly *pmult(poly *p1, poly *p2, int term1, int term2, int term, int *ptr)
{
poly *p3 = malloc(term * sizeof(poly));
int k = 0;
for (int i = 0; i < term1; i++) //Multiplies every poly1's term with every poly2's term and stores them in poly3
{
for (int j = 0; j < term2; j++)
{
p3[k].coeff = p1[i].coeff * p2[j].coeff;
p3[k++].expo = p1[i].expo + p2[j].expo;
}
}
printf("Displaying poly3:\n");
display(p3, k);
int max = p3[0].expo;
for (int i = 1; i < k; i++)
{
if (p3[i].expo > max)
{
max = p3[i].expo;
}
}
printf("\nMAXXXXX..........:%d\n", max);
int h = 0;
poly *p4 = malloc(k * sizeof(poly));
for (int i = max; i >= 0; i--) //if we have a polynomial result as 3X5+4X3+6X3+7X3+3X3+0X2 so we need to format it as 3X5+20X3+0X2
{
int sum = 0;
for (int j = 0; j < k; j++)
{
if (i == p3[j].expo)
{
sum += p3[j].coeff;
}
}
if (sum > 0)
{
p4[h].expo = i;
p4[h++].coeff = sum;
}
}
free(p3);
*ptr = h;
return p4;
}
void display(poly *p, int term)
{
printf("Printing a polynomial......\n");
for (int i = 0; i < term; i++)
{
printf("%dX%d + ", p[i].coeff, p[i].expo);
}
printf("\n");
}
int main()
{
int termp1, termp2;
printf("Enter the no of terms in polynomial one:");
scanf("%d", &termp1);
poly *poly1 = create(termp1);
display(poly1, termp1);
printf("Enter the no of terms in polynomial one:");
scanf("%d", &termp2);
poly *poly2 = create(termp2);
display(poly2, termp2);
int term = termp1 + termp2;
int ptr = 0;
poly *poly3 = pmult(poly1, poly2, termp1, termp2, term, &ptr);
display(poly3, ptr);
return 0;
}
计算多项式乘积的方法需要临时存储
termp1 * termp2
项,而不是预期的 termp1 + termp2
最大值。根据 C 库的报告,存储某些计算项时会出现缓冲区溢出、调用未定义的行为、破坏内存分配数据。