c - 减去 malloc 返回的大小为零的 2 个指针

标签 c malloc language-lawyer

我有一个队列数据结构定义为(为简单起见省略了NULL 检查)

struct ml_queue {
    void *buf;
    void *next_elemnt;
    size_t size;
}

struct ml_queue *ml_queue_alloc(size_t size){
    struct ml_queue *mq_ptr = malloc(sizeof(*mq_ptr));
    void *buf = malloc(size);
    ml_queue->buf = buf;
    ml_queue->size = size;
    ml_queue->next_element = buf;
    return ml_queue;
}

bool ml_queue_is_empty(struct ml_queue *queue){
    char *buf = queue->buf;
    char *next = queue->next;
    char *limit = buf + queue->size;
    return limit - buf > 0; //Here is the question
}

我不确定这样的实现是否会在使用零大小队列时导致 UB。喜欢

struct ml_queue *q = ml_queue_alloc(0);
bool is_empty = ml_queue_is_empty(q); //UB?

众所周知,malloc 返回一个大小为参数的对象。根据定义,数组不能为空。

但是我们可以认为 malloc(0) 分配了一个包含 1 个元素的零大小对象数组吗?该对象在标准的第 3.15 节中定义为

region of data storage in the execution environment, the contents of which can represent values

未指定可以为空。而数组和结构都不能包含零个成员。

最佳答案

malloc(0) 返回的是实现定义的行为。

根据 Implementation-defined behavior 上的 C11 标准 (n1570) 部分:

Whether the calloc, malloc, and realloc functions return a null pointer or a pointer to an allocated object when the size requested is zero (7.22.3).

因此您必须查找具体实现的文档才能回答这个问题。

关于c - 减去 malloc 返回的大小为零的 2 个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791132/

相关文章:

c - 我应该如何理解 "> outfile 2>&1"和 "2>&1 > outfile"?

c - 使用 malloc/free 时的 __lll_lock_wait_private ()

c++ - reinterpret_cast 创建一个简单的默认构造对象

c++ - 转换为不相关的引用类型是否违反了严格的别名规则?

c++ - SolFS 中这些函数的等价物?

使用指向 char 数组的指针转换结构

C- 比较运算符而不是 strcmp

c - 为什么在 C 中为数组声明动态分配的内存和指向数组声明的指针不一样?

c++ - malloc 没有按我的预期工作

c++ - 空的 variardic 枚举包——它们是否使两个函数不同?