我有点困惑,我的流程似乎是正确的,但我正在获取 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 行中,您在堆栈上创建了一个局部变量,当函数返回它时,作用域结束并且对象内存是空闲的。因此,如果您稍后使用该地址,则会出现段错误
关于C初始化结构并通过指针访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556866/