-2

i have a linked list in C which i need to destroy by request and keep memory allocation

here's the code :

can someone explain to me what exactly i need to add with the parameter dealloc?

    /** Destroy and de-allocate the memory hold by a list
\param list - a pointer to an existing list
\param dealloc flag that indicates whether stored data should also be de-allocated      
    */
    void dbllist_destroy(dbllist_t *list,dbllist_destroy_t dealloc)
    {
    dbllist_node_t *current = (dbllist_node_t *)malloc(sizeof(dbllist_node_t));
    dbllist_node_t *current = (dbllist_node_t *)malloc(sizeof(dbllist_node_t));

        if(current == NULL || temp == NULL)
            return -1;
        current = dbllist_tail(list);
        while (current != NULL)
        {
            temp = dbllist_prev(current);
            free(current);
            current = temp;
            dbllist_size(list)--;
        }
        free(current);
        free(temp);
        free(list);
        return 0;
    } 

    typedef enum { DBLLIST_LEAVE_DATA = 0, DBLLIST_FREE_DATA } dbllist_destroy_t;
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Og Lock
  • 23
  • 6

1 Answers1

0

So, remaining issues I can see:

  1. the double malloc at the top - all these will do is waste memory. There is no need to be allocing anything here.
  2. dbllist_size(list)-- is meaningless. you are simply getting a value and then reducing it. Presumably you are trying to reduce the stored size of the list. Either dbllist_size returns a pointer to the size (unlikely, but in which case you will need to do (*dbllist_size(list))--)). More likely you will either need to call a dbllist_set_size (if there is one) or (most likely) directly alter the size value (list->size-- or something similar). However, since you are deallocing the entire structure, you could just set size to 0 at the end^1
  3. The point you will want to dealloc the data is just before the free(current) in the middle. Probably it will be something like if (DBLLIST_FREE_DATA==dealloc) { free(dbllist_get_data(current));} (again, depends on the api)
  4. The free(current) after the for loop is not needed, as current must be null at this point.
  5. Checking for null at the top is good, but you are checking the wrong thing. You should be checking if list is null.
  6. You haven't declared temp

[^1]: if you needed destroy to be thread safe then you might want to set the size after freeing each item; in that case you would also want to put a mutex around the inside of the for loop. Also, since this is presumably a double linked list, you would want to updated the last/next pointers as well. Probably this is overkill for you though.

Oliver Matthews
  • 7,497
  • 3
  • 33
  • 36