Implement malloc-based SegmentAllocator #250

Merged
jwharm merged 1 commit from malloc-allocate into main 2025-07-14 21:49:47 +02:00
jwharm commented 2025-07-14 21:49:34 +02:00 (Migrated from github.com)

When a memory segment is passed to a native function with full ownership transfer, the native function will free the memory. Until now, java-gi used Arena.global() to allocate this memory, to prevent a double-free, but this is not guaranteed to work. It is better to actually use malloc to allocate the memory.

The malloc function we use is g_try_malloc0. This means the newly allocated memory will be zero-initialized. If the allocation fails, it returns null. In that case, java-gi will raise an InteropException.

The allocator contains a workaround to be able to allocate zero-length memory segments (common in Java, but not supported by g_malloc).

When a memory segment is passed to a native function with full ownership transfer, the native function will free the memory. Until now, java-gi used `Arena.global()` to allocate this memory, to prevent a double-free, but this is not guaranteed to work. It is better to actually use malloc to allocate the memory. The `malloc` function we use is `g_try_malloc0`. This means the newly allocated memory will be zero-initialized. If the allocation fails, it returns `null`. In that case, java-gi will raise an `InteropException`. The allocator contains a workaround to be able to allocate zero-length memory segments (common in Java, but not supported by `g_malloc`).
Sign in to join this conversation.
No description provided.