{"record":{"id":"32ac732eb2f857b1","repo":"java-native-access/jna","slug":"cannot-allocate-size-bytes","errorCode":null,"errorMessage":"Cannot allocate <size> bytes","messagePattern":"Cannot allocate <size> bytes","errorType":"exception","errorClass":"OutOfMemoryError","httpStatus":null,"severity":"critical","filePath":"src/com/sun/jna/Memory.java","lineNumber":119,"sourceCode":"        @Override\n        public String toString() {\n            return super.toString() + \" (shared from \" + Memory.this.toString() + \")\";\n        }\n    }\n\n    /**\n     * Allocate space in the native heap via a call to C's <code>malloc</code>.\n     *\n     * @param size number of <em>bytes</em> of space to allocate\n     */\n    public Memory(long size) {\n        this.size = size;\n        if (size <= 0) {\n            throw new IllegalArgumentException(\"Allocation size must be greater than zero\");\n        }\n        peer = malloc(size);\n        if (peer == 0)\n            throw new OutOfMemoryError(\"Cannot allocate \" + size + \" bytes\");\n\n        allocatedMemory.put(peer, new WeakReference<>(this));\n        cleanable = Cleaner.getCleaner().register(this, new MemoryDisposer(peer));\n    }\n\n    protected Memory() {\n        super();\n        cleanable = null;\n    }\n\n    /** Provide a view of this memory using the given offset as the base address.  The\n     * returned {@link Pointer} will have a size equal to that of the original\n     * minus the offset.\n     * @throws IndexOutOfBoundsException if the requested memory is outside\n     * the allocated bounds.\n     */\n    @Override\n    public Pointer share(long offset) {","sourceCodeStart":101,"sourceCodeEnd":137,"githubUrl":"https://github.com/java-native-access/jna/blob/d036ad9781adad4b66693e8fa7098e4ac665e0a3/src/com/sun/jna/Memory.java#L101-L137","documentation":"The Memory constructor throws this OutOfMemoryError when the underlying native malloc returns NULL (peer == 0), i.e. the OS/native allocator could not provide `size` bytes. Unlike a Java heap OOM, this reflects native heap exhaustion.","triggerScenarios":"new Memory(hugeSize) where the native heap cannot satisfy the request; cumulative native leaks exhausting the process address space; allocating on 32-bit JVMs beyond ~2-4GB addressable space.","commonSituations":"Allocating buffers sized from untrusted/oversized input; 32-bit processes; many live Memory instances never released (relying on Cleaner) causing native fragmentation/exhaustion; container memory limits making malloc fail.","solutions":["Reduce the requested allocation size or allocate in chunks.","Check process/container memory limits (ulimit, cgroups) and raise them.","Free Memory deterministically (close()/dispose or rely on explicit cleanup) instead of holding many allocations.","Switch to a 64-bit JVM/address space if on 32-bit.","Profile for native leaks; failing malloc after long runs usually means leaked native memory."],"exampleFix":"// before\nMemory buf = new Memory(totalSize); // totalSize ~ 4GB, malloc fails\n// after\nfor (Chunk c : chunks) { Memory buf = new Memory(c.size); /* process and release */ }","handlingStrategy":"fallback","validationCode":"static boolean sizePlausible(long bytes, long maxBytes) { return bytes > 0 && bytes <= maxBytes; }","typeGuard":null,"tryCatchPattern":"Memory m;\ntry {\n  m = new Memory(size);\n} catch (OutOfMemoryError e) {\n  if (e.getMessage().startsWith(\"Cannot allocate \")) {\n    m = allocateInChunks(size); // fall back to chunked allocation\n  } else throw e;\n}","preventionTips":["Cap allocation sizes based on trusted limits, not raw input.","Monitor native memory (Native.getNativeSize, OS RSS) in long-running apps.","Free Memory deterministically instead of waiting on the Cleaner.","Avoid 32-bit JVMs for large native allocations.","Check container/ulimit memory ceilings."],"tags":["jna","memory","out-of-memory","malloc"],"backgroundTag":"out-of-native-memory","analyzedSha":"d036ad9781adad4b66693e8fa7098e4ac665e0a3","analyzedAt":"2026-09-12T06:50:59.239Z","contentChangedAt":"2026-09-12T06:50:59.239Z","schemaVersion":2},"datasetVersion":"2026-09-14T11:17:12.474Z"}