C初始化结构并通过指针访问

标签 c arrays struct segmentation-fault

我有点困惑,我的流程似乎是正确的,但我正在获取 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/

相关文章:

python - 将 FILE * 传递给 Python/ctypes 中的函数

c - 传递引用导致段错误

objective-c - CoreFoundation 和一般指针

c - 我对 int 数组有相同的结构问题

我可以使用 cudaMalloc 分配比必要更多的内存以避免重新分配吗?

sql - 为什么我的查询结果随机返回?

arrays - 将数字数组转换为二进制数

c++ - 如何在cpp中使用头数组?

将字符串复制到结构体 C 中

c - C 结构的第一个字段是否总是保证偏移量为 0?