fix: addition of two polynomials memory leak and linked list crash (#1211)

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Bao Hexing 2023-03-14 01:44:01 +08:00 committed by GitHub
parent f0b38a3201
commit 62359492bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -30,17 +30,11 @@ struct term
*/ */
void free_poly(struct term *poly) void free_poly(struct term *poly)
{ {
if (!poly) while (poly)
{ {
return; // NULL pointer does not need delete struct term *next = poly->next;
} free(poly);
else poly = next;
{
while (!poly->next)
{
free(poly->next); // Deletes next term
}
free(poly); // delete the current term
} }
} }
@ -54,31 +48,19 @@ void free_poly(struct term *poly)
void create_polynomial(struct term **poly, int coef, int pow) void create_polynomial(struct term **poly, int coef, int pow)
{ {
// Creating the polynomial using temporary linked lists // Creating the polynomial using temporary linked lists
struct term *temp1, *temp2; struct term **temp1 = poly;
temp1 = *poly; // Contains the null pointer
// Initiating first term while (*temp1)
if (temp1 == NULL)
{ {
temp2 = (struct term *)malloc( temp1 = &(*temp1)->next;
sizeof(struct term)); // Dynamic node creation
temp2->coef = coef;
temp2->pow = pow;
// Updating the null pointer with the address of the first node of the
// polynomial just created
*poly = temp2;
temp2->next = NULL; // Increasing the pointer temp2
}
// Creating the rest of the nodes
else
{
temp2->next = (struct term *)malloc(
sizeof(struct term)); // Dynamic node creation
temp2 = temp2->next; // Increasing the pointer temp2
temp2->coef = coef;
temp2->pow = pow;
temp2->next = NULL;
} }
// Now temp1 reaches to the end of the list
*temp1 = (struct term *)malloc(
sizeof(struct term)); // Create the term and linked as the tail
(*temp1)->coef = coef;
(*temp1)->pow = pow;
(*temp1)->next = NULL;
} }
/** /**