C语言多项式乘法程序合并同次项时触发malloc(): corrupted top size段错误的解决求助
C语言多项式乘法程序合并同次项时触发malloc(): corrupted top size段错误的解决求助
大家好,我正在用C语言编写一个多项式乘法程序,已经实现了名为pmult的乘法函数。程序在完成多项式相乘的阶段都运行正常,但到了需要合并相同指数项的步骤时,突然触发了段错误,错误信息显示:malloc(): corrupted top size。我排查了好一会儿还是没找到问题根源,想请各位帮忙看看问题出在哪,该怎么解决?
我用来测试的多项式示例如下:
多项式p1(共5项)
| 系数 | 指数 |
|---|---|
| 2 | 6 |
| 5 | 3 |
| 3 | 2 |
| 2 | 1 |
| 3 | 0 |
多项式p2(共5项)
| 系数 | 指数 |
|---|---|
| 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; }
备注:内容来源于stack exchange,提问作者Harshal Malani




