I am trying to implement a Queue in C. Coming from Java and other managed languages, I am really struggling with memory management. Here is the enqueue()
function:
int enqueue(Queue q, int value) {
Node newNode = malloc(sizeof(Node));
/*newNode->value = value;
if (q->size == 0)
q->head = newNode;
else
q->head->next = &newNode;
q->size++;*/
}
I am getting this error :
malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
FWIW, here's the rest of the code (is this even right?):
typedef struct NodeStruct *Node;
struct NodeStruct {
Node* prev;
Node* next;
int value;
};
typedef struct QueueStruct *Queue;
struct QueueStruct {
Node* head;
Node* tail;
int size;
int capacity;
};
Queue newQueue(int size) {
Queue q = malloc(sizeof(Queue));
q->capacity = size;
q->size = 0;
q->head = NULL;
q->tail = NULL;
return q;
}
void printQueue(Queue q) {
printf("Queue of size %d, capacity %d", q->size, q->capacity);
}
int main() {
Queue myQ = newQueue(10);
// this seems to work
printQueue(myQ);
// epic fail
enqueue(myQ, 5);
return 0;
}
Why is this happening?