Search code examples
cqueuegstreamertailhead

Implementing a queue in C


I am trying to implement a custom queue for Gstreamer buffers. The problem is that when I try to dequeue, it seems that I am loosing the head of the queue. Whenever I try to dequeue twice, I get a segmentation fault. I have also noticed that head is always equal than head->next. Now I'm not sure if there's something wrong with enqueue or dequeue. Please help me out. Thank you.

typedef struct _GstBUFFERQUEUE GstBufferQueue;

struct _GstBUFFERQUEUE {
  GstBuffer *buf;
  guint buf_size;
  struct _GstBUFFERQUEUE *next;
};

void enqueue_gstbuffer(GstBufferQueue **head, GstBufferQueue **tail, guint *queue_size, GstBuffer *buf)
{
  if (*queue_size == 0)
  {
    *head = malloc(sizeof(GstBufferQueue));
    (*head)->buf = gst_buffer_try_new_and_alloc (GST_BUFFER_SIZE(buf));
    (*head)->buf = gst_buffer_copy(buf); 
    *tail = *head;
  }
  else
  {
    if ((*tail)->next = malloc(sizeof(GstBufferQueue))) {
        (*tail)->next->buf = gst_buffer_try_new_and_alloc (GST_BUFFER_SIZE(buf));
        (*tail)->next->buf = gst_buffer_copy(buf);
        (*tail) = (*tail)->next;
    }
    else {
        GST_WARNING("Error allocating memory for new buffer in queue");
    } 
  } 
  (*tail)->next = NULL; 
  (*queue_size)++;

}

void dequeue_gstbuffer(GstBufferQueue **head, GstBufferQueue **tail, guint *queue_size, GstBuffer **buf)
{
  GstBufferQueue **tmpPtr = head;
  GstBufferQueue **nextPtr;
  *nextPtr = (*head)->next; 
  *buf = gst_buffer_try_new_and_alloc (GST_BUFFER_SIZE((*tmpPtr)->buf));
  *buf = gst_buffer_copy((*tmpPtr)->buf);
  gst_buffer_unref((*tmpPtr)->buf);
  free((*tmpPtr));
  *head = *nextPtr;

  if ((*head) == NULL)
     (*tail) = NULL;

   (*queue_size)--;   
}

Solution

  • Replace

    GstBufferQueue **nextPtr;
    *nextPtr = (*head)->next;
    ...
    *head = *nextPtr;
    

    By

    GstBufferQueue *nextPtr;
    nextPtr = (*head)->next;
    ...
    *head = nextPtr;