0

I'm trying to call queue_t from my main function in order to give queue_t the size which I then intend to print out for test purpose .

Why does it say that my q is not initialized when I did in line 21 ?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct queue_t {

    char   *name;
    int     size;
    int  entries;
    double  time;
    struct packet_t **packets;
    int     read;
    int    write;
    long    lost;

};

struct queue_t *queue_create (char *name, int size) {

    int i;
    struct queue_t *q;
    q->size = size;
    q->name = name;
    printf("Name of queue: %s", q->name);
    printf("Size of queue: %d", q->size);

    return (q);
}


int main () {

    char *a = "Test";
    int size = 80;
    queue_create(a, size);

}
roschach
  • 8,390
  • 14
  • 74
  • 124
Faris
  • 3
  • 1
  • 1
    Line 21 is `struct queue_t *q;` which doesn't point anywhere that is defined, prior to dereferencing it in the following two lines. `q` is *uninitialised* with a value. – Weather Vane Jan 12 '19 at 19:23

1 Answers1

2
struct queue_t *q;
q->size = size;

The pointer q is clearly uninitialized here. And then you use it in q->size. You should assign/initialize a variable before using, ie. q = something;. Using an uninitialized pointer value might be undefined behavior.

You can:

struct queue_t *q = malloc(sizeof(*q));
if (q == NULL) { fprintf(stderr, "ERROR! malloc!\n"); abort(); }
q->size = size;

q is clearly assigned a value here, ie. the result of malloc() call. It allocates the memory for the queue_t on the heap. Remember to free() the pointer so that your program does not leak memory.

You also can allocate the memory for variable on the stack:

struct queue_t q_memory;
struct queue_t *q = &q_memory;
q->size = size;

But note that in this case the memory will be invalid after closing the block it was declared in, ie. after the }! So don't use it, if you want to return it from a function.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • why don't you use malloc like this tho ? struct queue_t *q = (struct queue_t *) malloc (sizeof(*q)); was there a specific reason to not assign a cast type? – Faris Jan 12 '19 at 20:41
  • [Don't cast the result of malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – KamilCuk Jan 12 '19 at 21:09