Question

We have to use the following declaration of a list:

typedef struct node {
    int val;
    struct node* next;
} node;

and write these functions:
1) node* add(int val, node* list) Inserts a new node at the beginning of the given list and returns it's pointer.
2) print(node* list) Prints the elements of the list.
3) delete(node* list) Deallocates all the elements of the given list
I'm not sure if I am correctly using the memory, but the code I wrote give a weird output :/ Can someone help me out ? Thanks

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int val;
    struct node* next;
} node;

node* aux;

node* add(int n, node* list){
   aux = malloc(sizeof(node));
   if(list==NULL){
      aux->val=n;
      aux->next=NULL;
      }
    else{
      aux->val=n;
      aux->next=list;
   }
   return aux;
}


void print(node* list){
   printf("[");
   while(list != NULL){
   if(list->next!=NULL)printf("%d, ",list->elem);
   else printf("%d",list->elem);
   list = list->next;
   }
printf("]\n");
}

void delete(node* list){
   list=NULL;
   //printf(list);  prints the expected output: []
}

/*EDIT: Correct function delete
void delete(node* list){
   while( list != null){
   node* temp = list->next;
   free(list);
   list=temp;
   }
}
*/ 

int main(){
   node* x = add(5, add(3, add(2, add(7, add(4, add(1, add(6, NULL)))))));
   print(x);
   delete(x);
   print(x); //still prints the initial list 
   return(0);
}
Was it helpful?

Solution

in

void delete(node* list){
   list=NULL;
   //printf(list);  prints the expected output: []
}

you set only the local variable (ie: parameter) list to be null, this does not affect the x from the outside world.

firstly, you should:

void delete(node** list){
   *list=NULL;
}

to set the x from main to NULL... however this does not FREE your list, the memory is still there and allocated (memory leak). You need to walk through the list and free all elements... this is your homework :)

Offtopic: Yes, I know this is C ... however calling a function delete is asking for trouble when this will be compiled with a C++ compiler ... tell this to your teacher. delete is a reserved keyword.

OTHER TIPS

Your delete function has two problems with it. First, your list = NULL assignment has no effect outside the function. Second, the function is not freeing memory properly. It should be walking down the list and free each node.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top