Tomasz Gebarowski

GList iterate and remove pattern

Recently I’ve came across a problem, when I had to iterate through a GList and remove its elements depending on some condition. This is the solution I came up with:

/* Set the iterator to the beginning of our list */
GList *node_itr = priv->_list;
while (node_itr != NULL)
   GObject *obj = (GObject *)node_itr->data;
   /* Store next element's pointer before removing it */
   GList *next = g_list_next(node_itr);
   /* Some dummy removal condition */
   if (my_gobject_marked_for_removal(obj))
      priv->_list = g_list_delete_link(priv->_list, node_itr);
   node_itr = next;