Skip to content

Commit a6493fa

Browse files
authored
fix: avoid OOM caused by NULL pointer returned from malloc(0) (#1822)
### Motivation It's left to the implementations of malloc if a `malloc(0)` returns a NULL pointer or a non-null pointer. However, our validation logic checks if a NULL pointer is returned and treats it as an OOM. ### Modification Always pass at least 1 to malloc, ensuring that we only get a NULL pointer if we're really out of memory. ### Result No more OOM errors thrown because of `malloc(0)` calls returning a NULL pointer.
1 parent fa6abf7 commit a6493fa

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

driver/impl/src/main/java/eu/cloudnetservice/driver/impl/network/netty/memory/MemorySegmentAllocator.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@ private static void validateAllocatedSegment(@NonNull MemorySegment segment, lon
7272
*/
7373
public static @NonNull MemorySegment malloc(long byteCount) {
7474
try {
75-
var segment = (MemorySegment) MALLOC.invokeExact(byteCount);
75+
// on malloc(0), implementations of malloc(3) have the choice to return either NULL or a unique non-null pointer
76+
// to ensure that we always get a non-null pointer that we can pass to free(1) we allocate at least one byte
77+
var segment = (MemorySegment) MALLOC.invokeExact(Math.max(1L, byteCount));
7678
validateAllocatedSegment(segment, byteCount);
7779
return segment.reinterpret(byteCount).fill((byte) 0);
7880
} catch (Throwable throwable) {

0 commit comments

Comments
 (0)