简体   繁体   中英

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

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?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM