gcc - C program acting weird -
i've started implementing circular queue in c, , have following lines of code:
#include <stdio.h> #include <stdlib.h> #include "cirq.h" //allocate circular queue cirq cq_alloc(void){ cirq cq = null; element *head; element *tail; if((head = malloc(sizeof(struct element*))) && (tail = malloc(sizeof(struct element *)))){ head->content = 0; // head node keeps track of size. tail->content = null; head->next = tail; tail->next = head; cq = &head; } else { printf("error: no space more cqueues.\n"); } return cq; } int cq_size(cirq q){ return (int)(*q)->content; } int main(){ cirq q = cq_alloc(); printf("size of element ptr %lu\n", sizeof(struct element *)); printf("%d\n", cq_size(q)); return 0; } now when compile , run program, having commented out line in main prints out sizeof(struct element *)), program runs fine , right size of queue, 0. when leave line in, size of struct printed out, after segmentation fault: 11. also, make things clear, struct element has void *data , struct element *next fields. how can adding in line prints stuff change behavior of program much?
edit: cirq.h
#ifndef cirq_h #define cirq_h typedef struct element **cirq; // cirq handle typedef struct element { void *content; struct element *next; } element; extern cirq cq_alloc(void);// allocate queue extern int cq_size(cirq q);// return size of queue extern void cq_enq(cirq q, void *value);// add value queue extern void *cq_deq(cirq q);// dequeue , return queue value extern void *cq_peek(cirq q);// return value @ queue head extern void cq_rot(cirq q);// requeue head element @ tail extern void cq_free(cirq q);// return space allocated queue #endif
it doesn't matter cirq is, fact return address of local object problem.
this here
cq = &head; is causing undefined behavior, because that's address of pointer head stored locally in function only, when function returns it's deallocated , invalid. using elsewhere (outside function) undefined behavior.
also, not typedef pointer. never that, let code reader know it pointer.
Comments
Post a Comment