When calling deleteQueue:
Exception thrown at 0x00007FF8E378169C (ucrtbased.dll) in LoadBalancer.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
Create queue function:
queue_t* createQueue(unsigned capacity){
queue_t* queue = (queue_t*)malloc(sizeof(queue_t));
if (queue == NULL)
{
return NULL;
}
queue->capacity = capacity;
queue->array = (char**)malloc(sizeof(char*) * queue->capacity);
queue->size = 0;
queue->front = 0;
queue->rear = -1;
InitializeCriticalSection(&(queue->cs));
return queue;
}
Enqueue:
void enqueue(queue_t* queue, char* string){
EnterCriticalSection(&(queue->cs));
if (isFull(queue)) {
LeaveCriticalSection(&(queue->cs));
return;
}
queue->rear = (queue->rear + 1) % queue->capacity;
queue->size = queue->size + 1;
char* ptr = (char*)malloc(strlen(string)+1);
memcpy(ptr, string, strlen(string)+1);
queue->array[queue->rear] = ptr;
LeaveCriticalSection(&(queue->cs));
return;
}
Delete queue function:
void deleteQueue(queue_t* queue){
DeleteCriticalSection(&(queue->cs));
if (queue != NULL)
{
for (int i = 0; i < queue->capacity; i++) {
free(queue->array[i]);
}
free(queue->array);
free(queue);
}
}
And should I free the pointer as well in dequeue program breaks with the same exception?
char* dequeue(queue_t* queue){
EnterCriticalSection(&(queue->cs));
if (isEmpty(queue)) {
LeaveCriticalSection(&(queue->cs));
return NULL;
}
char* temp = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size = queue->size - 1;
LeaveCriticalSection(&(queue->cs));
return temp;
}
For starters you allocated an array of pointers that has indeterminate values.
queue->array = (char**)malloc(sizeof(char*) * queue->capacity);
So using this loop within the function deleteQueue
for (int i = 0; i < queue->capacity; i++) {
free(queue->array[i]);
}
can invoke undefined behavior. You should initialize the array with a null pointer. For example instead of using the function malloc
you could use the function calloc
.
Secondly within the function dequeue
after this statement
char* temp = queue->array[queue->front];
you should write
queue->array[queue->front] = NULL;
It is the responsibility of the user to free the returned string.