add queue_free and return a copy of the data to the user

This commit is contained in:
jacekpoz 2024-03-10 12:47:38 +01:00
parent dc368f088a
commit a877419d69
Signed by: poz
SSH key fingerprint: SHA256:JyLeVWE4bF3tDnFeUpUaJsPsNlJyBldDGV/dIKSLyN8
3 changed files with 14 additions and 1 deletions

View file

@ -8,6 +8,8 @@ typedef struct Queue Queue;
Queue *queue_new(size_t size, size_t element_size);
void queue_free(Queue *queue);
void *queue_read(Queue *queue);
bool queue_write(Queue *queue, void *value);

View file

@ -28,7 +28,10 @@ int main(void) {
long val = *(long*)val_ptr;
printf("%zu: read %ld from fifo\n", i, val);
free(val_ptr);
}
queue_free(q);
return 0;
}

View file

@ -22,12 +22,20 @@ Queue *queue_new(size_t size, size_t element_size) {
return ret;
}
void queue_free(Queue *q) {
for (size_t i = q->front; i < q->back; ++i) {
free(q->data[i]);
}
free(q->data);
free(q);
}
void *queue_read(Queue *q) {
if (q->front == q->back) {
return NULL;
}
void* ret = q->data[q->front];
void* ret = memcpy(malloc(q->element_size), q->data[q->front], q->element_size);
q->data[q->front] = NULL;
q->front = (q->front + 1) % q->size;