linked list - In C why does my clearList function not work -
i'm trying clear list. keep getting error says free() called on unallocated pointer current. i'm not sure problem have seen multiple sites use code.
this whole program upon request: suppose fill in these 3 functions.
#include "orderedlist.h" node *orderedinsert(node *p, int newval) /* allocates new node data value newval , inserts ordered list first node pointer p in such way data values in modified list in nondecreasing order list traversed. */ { node * q = null; q = (node*)malloc(sizeof(node)); q->data = newval; q->next = null; if (q == null) { return q; } if (p == null || newval <= p->data ) { q->next = p->next; return q; } node *tmp, *last; tmp = (node*)malloc(sizeof(node)); tmp = p; while (tmp->next != null && tmp->data <= newval) { last = tmp; tmp = tmp->next; } q->next = tmp; last->next = q; return p; } void printlist(file *outfile, node *p) /* prints data values in list first node pointer p first last, space between successive values. prints newline @ end of list. */ { node* temp = p; while(temp != null) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } void clearlist(node **p) /* deletes nodes in list first node pointer *p, resulting in *p having value null. note passing pointer address can modify pointer. */ { node* current = *p; node* temp; while(current != null) { temp = current->next; free(current); current = temp; } *p = null; }
sample code
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct node { int data; struct node *next; } node; node *orderedinsert(node *p, int newval){ node *q; if(null==(q = (node*)malloc(sizeof(node)))){ perror("malloc"); exit(exit_failure); } q->data = newval; q->next = null; if (p == null || newval <= p->data ){ q->next = p; return q; } node *tmp = p, *last; while (tmp != null && tmp->data < newval) { last = tmp; tmp = tmp->next; } q->next = tmp; last->next = q; return p; } void printlist(file *outfile, node *p){ node* temp = p; while(temp != null){ fprintf(outfile, "%d ", temp->data); temp = temp->next; } fprintf(outfile, "\n"); } void clearlist(node **p){ node* current = *p; while(current != null){ node *temp = current->next; free(current); current = temp; } *p = null; } int main (void){ node *head = null; int i, v; printf("the generated number\n"); for(i=0; i<10; ++i){ v = rand()%10; printf("%d ", v); head = orderedinsert(head, v); } printf("\n"); printf("the orderd number\n"); printlist(stdout, head); clearlist(&head); return 0; }
Comments
Post a Comment