Skip to content

Commit 6235949

Browse files
Bao HexingPanquesito7
andauthored
fix: addition of two polynomials memory leak and linked list crash (#1211)
Co-authored-by: David Leal <[email protected]>
1 parent f0b38a3 commit 6235949

File tree

1 file changed

+14
-32
lines changed

1 file changed

+14
-32
lines changed

misc/poly_add.c

Lines changed: 14 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,11 @@ struct term
3030
*/
3131
void free_poly(struct term *poly)
3232
{
33-
if (!poly)
33+
while (poly)
3434
{
35-
return; // NULL pointer does not need delete
36-
}
37-
else
38-
{
39-
while (!poly->next)
40-
{
41-
free(poly->next); // Deletes next term
42-
}
43-
free(poly); // delete the current term
35+
struct term *next = poly->next;
36+
free(poly);
37+
poly = next;
4438
}
4539
}
4640

@@ -54,31 +48,19 @@ void free_poly(struct term *poly)
5448
void create_polynomial(struct term **poly, int coef, int pow)
5549
{
5650
// Creating the polynomial using temporary linked lists
57-
struct term *temp1, *temp2;
58-
temp1 = *poly; // Contains the null pointer
51+
struct term **temp1 = poly;
5952

60-
// Initiating first term
61-
if (temp1 == NULL)
53+
while (*temp1)
6254
{
63-
temp2 = (struct term *)malloc(
64-
sizeof(struct term)); // Dynamic node creation
65-
temp2->coef = coef;
66-
temp2->pow = pow;
67-
// Updating the null pointer with the address of the first node of the
68-
// polynomial just created
69-
*poly = temp2;
70-
temp2->next = NULL; // Increasing the pointer temp2
71-
}
72-
// Creating the rest of the nodes
73-
else
74-
{
75-
temp2->next = (struct term *)malloc(
76-
sizeof(struct term)); // Dynamic node creation
77-
temp2 = temp2->next; // Increasing the pointer temp2
78-
temp2->coef = coef;
79-
temp2->pow = pow;
80-
temp2->next = NULL;
55+
temp1 = &(*temp1)->next;
8156
}
57+
58+
// Now temp1 reaches to the end of the list
59+
*temp1 = (struct term *)malloc(
60+
sizeof(struct term)); // Create the term and linked as the tail
61+
(*temp1)->coef = coef;
62+
(*temp1)->pow = pow;
63+
(*temp1)->next = NULL;
8264
}
8365

8466
/**

0 commit comments

Comments
 (0)