[英]calloc() to a pointer in struct doesn't work on clang [on hold]
我在 C 中實現了一個隊列。 考慮下面的代碼:
#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;
}
我使用 calloc() 來初始化結構中的一個數組,但是該數組的某些值不為零。
$ clang -Wall -O0 -g -o queue.o queue.c && ./queue.o
952118112
32728
0
0
0
0
0
0
0
0
0
0
這是為什么?
本memory配置
queue* q = malloc(sizeof(q));
是錯的。 它僅將 memory 分配給一個指針,而不是為隊列類型的 object 分配。
改寫
queue* q = malloc(sizeof(*q));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.