From 31162bf4261b2e740f6e26f2c2f22c36d3556cf0 Mon Sep 17 00:00:00 2001 From: HASUMI Hitoshi Date: Sat, 1 Feb 2025 14:49:33 +0900 Subject: [PATCH] [ruby/prism] Handle zero-sized allocation in pm_constant_id_list_init_capacity According to the calloc(3) man page, when nmemb or size is 0, `calloc()` can either return NULL or a unique pointer that can be passed to `free()`. While gcc and clang typically return a unique pointer, mruby's `mrb_calloc()` returns NULL in this case. Since `pm_constant_pool_init()` is commonly called with capacity=0 during normal operation of Prism, explicitly handle this case by setting `list->ids` to NULL when capacity is 0. This approach is portable across different calloc implementations and avoids potential issues with mruby's allocation behavior. This maintains compatibility with `free()` and `realloc()`, as passing NULL pointers to these functions is explicitly allowed by their specifications. https://github.com/ruby/prism/commit/1c32252df7 --- prism/util/pm_constant_pool.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/prism/util/pm_constant_pool.c b/prism/util/pm_constant_pool.c index 624002cec9..38ea01a228 100644 --- a/prism/util/pm_constant_pool.c +++ b/prism/util/pm_constant_pool.c @@ -15,8 +15,12 @@ pm_constant_id_list_init(pm_constant_id_list_t *list) { */ void pm_constant_id_list_init_capacity(pm_constant_id_list_t *list, size_t capacity) { - list->ids = xcalloc(capacity, sizeof(pm_constant_id_t)); - if (list->ids == NULL) abort(); + if (capacity) { + list->ids = xcalloc(capacity, sizeof(pm_constant_id_t)); + if (list->ids == NULL) abort(); + } else { + list->ids = NULL; + } list->size = 0; list->capacity = capacity;