[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
This commit is contained in:
HASUMI Hitoshi 2025-02-01 14:49:33 +09:00 committed by git
parent 127325a4ba
commit 31162bf426

View File

@ -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;