doubly linked list freeing memory valgrind error

Hi I'm trying to free the memory that I was allocated in the doubly linked list but when I check it with valgrind I have some error in the free_all function ( I think ) but I don't know how to avoid it.

I think in the free_all function I'm using temp and node pointer wrong or I need to allocate it first and then use them, but when I've tried this method valgrind still gave me some error.

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

/*
  to compile it:
  gcc -g -Wall -ggdb3  double_linkedlist2.c -o double_linkedlist
  to check for memory leak and error:
  valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out.txt ./double_linkedlist
*/
typedef struct listitem
{
  struct listitem *next;    // pointer to next item
  struct listitem *prev;    // pointer to previous item
  int data;                 // some data
} ITEM;


int main (void)
{
  // prototype functions
  void free_all (ITEM *lst_ptr);


  // Variables
  ITEM *p_temp, *head;

  head = malloc (sizeof (ITEM));  // head will keep first and last element in its pointers
  head -> next = head;            // the last element in the list (at first head -> next and head -> prev will point to the head)
  head -> prev = head;            // the first element in the list


     for (int i = 0; i < 3; i++)
       {
         p_temp = malloc (sizeof (ITEM));     // allocate some memory for the new list item
         p_temp -> data = i;                  // set the list item's data to the loop count so that we can see where it is in the list
         p_temp -> next = head -> next;          // this will insert at the FRONT of the list
         head -> next = p_temp;                  // and set the list head to the newly created list item
         p_temp -> prev = head;              // this will insert at the BACK of the list
         p_temp -> next -> prev = p_temp;       // and set the list 'tail' to the newly created item
       }

     // now let's see what we got going forward
     printf ("Going forward\n");
     p_temp = head -> next;

     while (p_temp != head)
       {
         printf ("forward list item: current is %p; next is %p; prev is %p; data is %d\n", p_temp, p_temp -> next, p_temp -> prev, p_temp -> data);
         p_temp = p_temp -> next;
       }

     // now let's see what we got going backward
     printf ("Going backwards\n");
     p_temp = head -> prev;

     while (p_temp != head)
       {
         printf ("backward list item; current is %p; next is %p; prev is %p; data is %d\n", p_temp, p_temp -> next, p_temp -> prev, p_temp -> data);
         p_temp = p_temp -> prev;
       }

     printf ("\n");
     free_all (head);

     return 0;
}

void free_all (ITEM *head)
{
  ITEM *temp, *node;

  node = head;

  while (node != head -> prev)
    {
      temp = node;
      printf ("freed list item: current is %p; next is %p; prev is %p; data is %d\n", temp, temp -> next, temp -> prev, temp -> data);
      node = node -> next;
      free (temp);
    }
  free (node);
  free (head);
}

your free_all has at least two errors: the while condition references head->prev, but in the first iteration you free head (use after free). after you exit the loop, you free head despite having free'd it in the first iteration. free_all() does work for the single element case.

c - doubly linked list freeing memory valgrind error, your free_all has at least two errors: the while condition references head->prev, but in the first iteration you free head (use after free). after you  I am currently working on a project to implement a doubly linked list with the nodes as structures that hold MP3 information. I believe I have, for the most part, correctly implemented the data structure. The issue I am having is through a feature I am trying to implement.

There was no error or memory leak in valgrind after this modification

void free_all (ITEM *head)
{
  ITEM *temp, *node = NULL;

  node = head -> next;

  while (node != head -> prev)
    {
      temp = node;
      printf ("freed list item: current is %p; next is %p; prev is %p; data is %d\n", node, node -> next, node -> prev, node -> data);
      node = node -> next;
      free (temp);
    }

  node = head -> prev;
  printf ("freed list item: current is %p; next is %p; prev is %p; data is %d\n", node, node -> next, node -> prev, node -> data);
  free (head);
  free (node);
}

Doubly linked list with no apparent memory leaks, I've run my code through Valgrind and managed to not get any memory leaks based The most obviously wrong is the use of double-pointers everywhere. If any given list contains only one data type, the problem is lessened, but could mislead a user into thinking that those functions free the memory. Linked lists are inherently dynamic data structures; they rely on new and delete (or malloc and free) for their operation. Normally, dynamic memory management is provided by the C/C++ standard library, with help from the operating system. However, nothing stops us from writing our own allocator, providing the same services as malloc and free.

This post was written by mevets as an edit to my solution but I thought it would be better to include this to the thread as well:

mevets:

I would tend towards something like:

void Unlink(ITEM **head, ITEM *t) {
        if (t->next == t) {
                /* remove head */
                *head = NULL;
        } else {
                t->prev->next = t->next;
                t->next->prev = t->prev;
                if (t == *head) {
                        *head = t->next;
                }
        }
}

/*
   remove and return the element after head
*/
ITEM *Pop(ITEM **head) {
        ITEM *node;
        if ((node = *head) != NULL) {
                node = node->next;
                Unlink(head, node);
        }
        return node;
}


void free_all (ITEM *head) {
        ITEM *node;
        while ((node = Pop(&head)) != NULL) {
            free(node);
        }
}

which separates out the list maintenance (Unlink) from the ordering (Pop) and the memory management (free_all). This leaves you with more boundaries where you could make assertions about the list, for examaple pre and post Unlink, the list should be valid and could be checked. Also, if there was concurrent access to the list, you could bracket Pop() with a lock, to minimize conflict.

A caching allocator is a thing itself, but a typical part of the contract is you release nodes in a known state so it can skip the construction of them when they are re-allocated.

How to fix "Invalid read of size 8" valgrind error for doubly linked list , How to fix "Invalid read of size 8" valgrind error for doubly linked list code? The implementation of the data structure and the clearing of memory upon for the node and I make sure to free the fields first, and then the node. For an 'auto free' pool, VALGRIND_MEMPOOL_FREE will automatically free the second level blocks that are contained inside the first level block freed with VALGRIND_MEMPOOL_FREE. In other words, calling VALGRIND_MEMPOOL_FREE will cause implicit calls to VALGRIND_FREELIKE_BLOCK for all the second level blocks included in the first level block.

[PDF] CS61, Fall 2012 Section 2 Notes, Common Memory Errors When Using Malloc. How can you Checking if a node is in a Doubly Linked List. 4: Garbage in C: must manage explicitly with malloc​() and free(). #include Valgrind tells you that you have an uninitialized value!! Doubly Linked List implementation in C. GitHub Gist: instantly share code, notes, and snippets.

Doubly Linked List implementation in C · GitHub, //Inserts a Node at head of doubly linked list This is due to using malloc in the function GetNewNode, but the allocated memory isn't freed in the end. at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==10234== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0). Implementation of a generic (a.k.a. data type agnostic) singly linked list in C with Unity unit tests and a Valgrind check for memory leaks. This is a toy project to learn test case development using Unity and get a feel for a flow where test cases drive implementation and serve as a debugging and verification tool during development.

CS50x, But, since x is in a location outside of the memory we've allocated, eventually we In the code above, we would have to both fix the faulty index and then free() the allocated memory. P.S. The name “Valgrind” is a reference to the main entrance of To solve this same problem with a linked list of nodes:  \$\begingroup\$ I don't think it is with free_list but running Valgrind gives some memory leak errors init_node and init_list \$\endgroup\$ – Dair Aug 24 '16 at 5:58 \$\begingroup\$ You can mimic OOP's classes with providing a pointer to a print function in the element struct.

Comments
  • Did you use pen and paper to play a few scenarios of your code?
  • Hint: start debugging the creation of your list. It looks very fishy. Learn how to use your debugger. Reading this may help as well.
  • thank you so much for the help I solved it, but is there any way to make it better
  • My preference is to remove the list items one at a time, and free them. That way, this list can be verified at each iteration, it minimizes the critical section if you need concurrent access, and facilitates an object based caching allocator (ie. Solaris slabs).
  • I'm just learning to how to work with basic pointers and I'm really novice at that. If it's no trouble, is it possible to show me how I could write my free_all function by slab allocation in an example by code?