c - Freeing an array within a struct -
for assignment have write circular queue (which imagine of familiar with). made structure , function initializes queue struct using dynamic memory. note have array arr within struct assign memory.
for reason can't seem free array memory.
struct queue { element_t *arr; // dynamic array containing data elements int current_size; // counts number of elements in queue int front, rear; // remark later: fields need added here make thread-safe queue needed assigment }; queue_t* queue_create(){ struct queue *queue = malloc(sizeof(struct queue)); if(queue == 0){ //check if memory available printf("out of memory\n"); return null; } queue -> current_size = 0; queue -> front = -1; queue -> rear = -1; queue -> arr = malloc(queue_size*sizeof(element_t)); return queue; }
i'm trying free memory when i'm done using function queue_free. function takes in double pointer queue (part of assignment).
void queue_free(queue_t** queue){ free(**queue -> arr); free(*queue); }
when call last function got error message saying:
queue.c: in function ‘queue_free’: queue.c:39:16: error: request member ‘arr’ in not structure or union free(**queue -> arr); ^
i've checked valgrind leaks. queue gets freed correctly reason can't address of array.
thanks in advance
p.s. free(queue -> arr); free(*queue -> arr); , free(**queue -> arr); fail , generate same error message.
the free statement should free((*queue)->arr)
.
explanation: queue_free
defines queue
variable pointer pointer queue_t
struct. now, in order pointer struct need remove 1 level of indirection using (*queue)
; can use dereference operator ->
access arr
member.
now, reason why other options didn't work are:
free(queue -> arr)
- pointer pointer of queue_t structure not havearr
memberfree(*queue -> arr)
- dereference operator ('*'
) refers whole expression, i.e.queue->arr
, takes previous errorfree(**queue -> arr)
- same above
Comments
Post a Comment