I wrote a C program to practice DSA, specifically queues.
I wrote a function free_q() to free the dynamically allocated memories, but when I print the pointer to these structures, I get a memory address that is not equal to when I print %p NULL. I'd like to know why isn't the pointer Q set to NULL when freeing not only the dynam. all. structure but also the pointer to the array inside the structure.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct queue_rec
{
unsigned int front;
unsigned int rear;
unsigned int max_size;
unsigned int size;
int *arr_struct;
};
typedef struct queue_rec *QUEUE;
int
isEmpty(QUEUE Q)
{
return(Q->size==0);
}
int isFull(QUEUE Q)
{
return(Q->size>=Q->max_size);
}
QUEUE
create_queue(unsigned int size)
{
QUEUE Q = (QUEUE) malloc(sizeof(struct queue_rec));
if(Q==NULL){printf("Out of space!");}
else
{
Q->arr_struct = (int *) malloc(size * sizeof(int));
if(Q->arr_struct == NULL){printf("Out of space!");}
else
{
Q->size = 0;
Q->front = 1;
Q->rear = 0;
Q->max_size = size;
}
}
return Q;
}
unsigned int
succ(unsigned int value, QUEUE Q)
{
if(++value==Q->max_size){value=0;}
return value;
}
void
enqueue(int data, QUEUE Q)
{
if(isFull(Q)){printf("Queue is full!");}
else
{
Q->size++;
Q->rear = succ(Q->rear, Q);
Q->arr_struct[Q->rear] = data;
}
}
void
dequeue(QUEUE Q)
{
if(isEmpty(Q)){printf("Queue is empty!");}
else
{
Q->size--;
printf("%d", Q->arr_struct[Q->front]);
Q->front = succ(Q->front,Q);
}
}
void
free_q(QUEUE Q)
{
free(Q->arr_struct);
free(Q);
Q = NULL;
}
int main()
{
QUEUE Q = create_queue(4);
free_q(Q);
printf("%p\c", Q);
printf("%p", NULL);
return 0;
}
OUTPUT:
00031480
00000000