Skip to content

Commit 1c32252

Browse files
committed
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.
1 parent a46edfd commit 1c32252

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

src/util/pm_constant_pool.c

+6-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,12 @@ pm_constant_id_list_init(pm_constant_id_list_t *list) {
1515
*/
1616
void
1717
pm_constant_id_list_init_capacity(pm_constant_id_list_t *list, size_t capacity) {
18-
list->ids = xcalloc(capacity, sizeof(pm_constant_id_t));
19-
if (list->ids == NULL) abort();
18+
if (capacity) {
19+
list->ids = xcalloc(capacity, sizeof(pm_constant_id_t));
20+
if (list->ids == NULL) abort();
21+
} else {
22+
list->ids = NULL;
23+
}
2024

2125
list->size = 0;
2226
list->capacity = capacity;

0 commit comments

Comments
 (0)