Reputation: 131
Wanted to check with the community on implementing a queue in C and malloc
when adding a new node.
When I create a node
/process
in my code, I allocate memory at the point I create the process. However, when I look at various implementations of a queue, I noticed that when adding to the queue i.e. void push_back(struct*);
, I've noticed that some implementations allocate / malloc
when adding a new node to the tail of the queue. If I already allocate the dynamic memory at the point I create the struct
, do I need to malloc
space when calling the function push_back(struct*)
? My example below does not.
typedef struct process{
int pid;
struct process* next;
} Process;
typedef struct Queue{
Process* head;
Process* tail;
}Queue;
void push_back(Queue *q, Process *p){
p->next = NULL;
if( q->head == NULL && q->tail ==NULL){
q->head = q->tail = p;
}
else {
q->tail->next = p;
q->tail = p;
}
}
Upvotes: 1
Views: 1843
Reputation: 2616
You're implementation is OK and you don't have to allocate inside push_back() if you allocated when created. Don't confuse between the memory allocation of the new created Process, and the memory allocation of the pointer that is going to point to the new Process: The new created process should be alloced (in your implementation it should be allocated outside of push_back()). The pointer that is going to point to the new Process was already allocated while the previous Process was created! The pointer itself (only sizeof an address).
About the allocation responsibility, i.e. who should do this or where it should be done - if push_back() argument is pointer to Process it's more reasonable that it will be allocated outside, by the "user" of this function. In another implementation you could define push_back() argument as only the content of Process, i.e. pid. Then it would make more sense for Process to be allocated inside push_back().
Upvotes: 1
Reputation: 135
No, you don't need to allocate more memory. The memory was already allocated; your queue consists of pointers.
One problem with this is that the queue most likely will not be laid out consecutively in memory. If you leave memory allocation up to your queue implementation, you can control when and where memory is allocated, allowing for better performance when accessing elements.
Upvotes: 0