Search code examples
cmallocclangcalloc

calloc() to a pointer in struct doesn't work on clang


I have implemented a queue in C. Consider the below code:

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

typedef struct queue queue;
struct queue {
  int len;
  int head;
  int tail;
  int* array;
};

int main(int argc, char* argv[argc+1]) {
  int len = 12;
  queue* q = malloc(sizeof(q));
  *q = (queue){
    .array = calloc(len, sizeof(int)),
    .len = len,
  };
  for (int i = 0; i < len; i += 1) {
    printf("%d\n", q->array[i]);
  }
  free(q->array);
  free(q);
  return EXIT_SUCCESS;
}

I used calloc() to initialize an array in the structure, but some values of the array are not zero.

$ clang -Wall -O0 -g -o queue.o queue.c && ./queue.o
952118112
32728
0
0
0
0
0
0
0
0
0
0

Why is that?


Solution

  • This memory allocation

    queue* q = malloc(sizeof(q));
    

    is wrong. It allocates the memory only for a pointer not for an object of the type queue.

    Write instead

    queue* q = malloc(sizeof(*q));