fix writing to the queue using the same value
the fix was to memcpy the passed pointer to a local one and it works :-)
This commit is contained in:
parent
e58facd03e
commit
dc368f088a
3 changed files with 8 additions and 4 deletions
|
@ -6,7 +6,7 @@
|
||||||
|
|
||||||
typedef struct Queue Queue;
|
typedef struct Queue Queue;
|
||||||
|
|
||||||
Queue *queue_new(size_t size);
|
Queue *queue_new(size_t size, size_t element_size);
|
||||||
|
|
||||||
void *queue_read(Queue *queue);
|
void *queue_read(Queue *queue);
|
||||||
|
|
||||||
|
|
|
@ -7,7 +7,7 @@
|
||||||
int main(void) {
|
int main(void) {
|
||||||
srand((unsigned int)time(NULL));
|
srand((unsigned int)time(NULL));
|
||||||
|
|
||||||
Queue *q = queue_new(51);
|
Queue *q = queue_new(51, sizeof(long));
|
||||||
|
|
||||||
for (size_t i = 0; i < 50; ++i) {
|
for (size_t i = 0; i < 50; ++i) {
|
||||||
long val = rand() % 1000;
|
long val = rand() % 1000;
|
||||||
|
|
|
@ -1,19 +1,22 @@
|
||||||
#include <queue.h>
|
#include <queue.h>
|
||||||
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
struct Queue {
|
struct Queue {
|
||||||
size_t back;
|
size_t back;
|
||||||
size_t front;
|
size_t front;
|
||||||
size_t size;
|
size_t size;
|
||||||
|
size_t element_size;
|
||||||
void **data;
|
void **data;
|
||||||
};
|
};
|
||||||
|
|
||||||
Queue *queue_new(size_t size) {
|
Queue *queue_new(size_t size, size_t element_size) {
|
||||||
Queue *ret = malloc(sizeof(Queue));
|
Queue *ret = malloc(sizeof(Queue));
|
||||||
ret->back = 0;
|
ret->back = 0;
|
||||||
ret->front = 0;
|
ret->front = 0;
|
||||||
ret->size = size;
|
ret->size = size;
|
||||||
|
ret->element_size = element_size;
|
||||||
ret->data = malloc(size * sizeof(void*));
|
ret->data = malloc(size * sizeof(void*));
|
||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
|
@ -36,7 +39,8 @@ bool queue_write(Queue *q, void *value) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
q->data[q->back] = value;
|
void *local_value = memcpy(malloc(q->element_size), value, q->element_size);
|
||||||
|
q->data[q->back] = local_value;
|
||||||
q->back = (q->back + 1) % q->size;
|
q->back = (q->back + 1) % q->size;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
Loading…
Reference in a new issue