[英]C initialize struct and access by pointer
我有點困惑,似乎我的流量是正確的,但我得到Seg。 故障(第15行)
標題中的結構:
typedef struct ringBuf_t {
uint32_t data[BUF_CAPACITY];
int head;
int tail;
uint32_t capacity;
} ringBuf_t;
以及我如何使用它:
ringBuf_t *create() {
ringBuf_t buf = {.capacity = BUF_CAPACITY, .head = 0, .tail = 0};
return &buf;
}
int push(ringBuf_t *buf, uint32_t item) {
if (buf->head + 1 == buf->tail) {
return -1;
}
buf->data[buf->head] = item;
buf->head = (buf->head + 1) % buf->capacity;
return 0;
}
在第5行中,您在堆棧上創建一個局部變量,當函數返回它時,作用域結束並且對象內存空閑。 因此,如果您稍后使用該地址,則會出現seg-fault
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.