我有一个队列数据结构定义为(为简单起见省略了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
, andrealloc
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/