CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Creating a new queue

We'd like our large programs to have more than a single queue - thus we don't want a single, global, variable, and we don't know until run-time how many queues we'll require.

We thus need a function to allocate space for, and to initialize, a new queue:


QUEUE *queue_new(void)
{
    QUEUE *q = malloc( sizeof(QUEUE) );

    if(q == NULL) {
        perror( __func__ );
        exit(EXIT_FAILURE);
    }
    q->head    = NULL;
    q->tail    = NULL;

    return q;
}

    ....
    QUEUE  *people_queue  =  queue_new();
    QUEUE  *truck_queue   =  queue_new();


QUEUE *queue_new(void)  //  same outcome, often seen
{
    QUEUE *q = calloc( 1, sizeof(QUEUE) );

    if(q == NULL) {
        perror( __func__ );
        exit(EXIT_FAILURE);
    }
    return q;
}







If we remember that:
  • the calloc function both allocates memory and sets all of its bytes to the zero-bit-pattern, and
  • that (most) C11 implementations represent the NULL pointer as the zero-bit-pattern,
then we appreciate the simplicity of allocating new items with calloc.

 


CITS2002 Systems Programming, Lecture 19, p14, 3rd October 2023.