0

I have written a function Serve to get the front node in the queue and remove it. It is as follows:

void Serve(QueueNode **p,Queue *q)
{
    if(QueueEmpty(q))
        Error("Queue is empty!");
    else
    {
        if(q->front==q->rear)
        {
            *p=q->front;
            q->front=q->rear=NULL;
        }
        else{
            *p=(q->front);
            q->front=q->front->next;
            (*p)->next=NULL;
        }
    }
}

I call it from the main function as follows:

int main() {
    QueueNode **p=malloc(sizeof(QueueNode));
    Queue *q=CreateQueue();
    Append('a',q);
    Append('b',q);
    Append('c',q);
    Append('d',q);
    Serve(p,q);
}

While declaring the pointer to pointer QueueNode, if I set it to NULL or leave it uninitialized the program gave me NULL pointer dereference or accessing wrong memory location. I can understand why. But, here, when I create the QueueNode using malloc in this line:

QueueNode **p=malloc(sizeof(QueueNode));

the space allocated is getting wasted when I reassign it to q->front in the Serve function. How can I save this space. Also, I just need a pointer that points to q->front. Thanks !

10
  • Sorry I need a pointer that points to q->front ! Commented Aug 28, 2017 at 16:19
  • 1
    Please create a minimal reproducible example. The malloc() probably isn't needed at all, but no way to be sure without having a self-contained example. Commented Aug 28, 2017 at 16:19
  • 2
    @BLUEPIXY That leaks a QueueNode. There is no need to malloc a node. It should be QueueNode* p = NULL. Commented Aug 28, 2017 at 16:19
  • 1
    @Banex what is nullptr? You mean NULL? Commented Aug 28, 2017 at 16:20
  • 2
    QueueNode **p=malloc(sizeof(QueueNode)); this is wrong, no matter what. It should be sizeof(QueueNode *) or better just sizeof *p. But then, as I already said, I don't see why you're allocating memory here at all. Commented Aug 28, 2017 at 16:26

1 Answer 1

1

you don't need allocate memory for p. it's already allocated in function Append().

int main() {
    QueueNode *p=NULL; 
    Queue *q=CreateQueue(); 
    Append('a',q); 
    Append('b',q); 
    Append('c',q); 
    Append('d',q); 
    Serve(&p,q); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.