whoami

Lucas Jenß

cat /etc/motd

The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.

Close-up of white dominoes with black dots standing on green felt surface, shallow depth of field, focused mood

ls -la ~/languages/

total 8
drwxr-xr-x
▶ PHP
▶ Ruby
▶ Scala
▶ C#
▶ JavaScript
▶ Objective-C
▶ Shell Scripting

ls -la ~/toolchain/

total 7
drwxr-xr-x
▶ Typo3
▶ Akka
▶ Capistrano
▶ Git
▶ MAMP
▶ Adobe Illustrator
▶ NSTrackingArea (Cocoa)

uname -a

platforms
drwxr-xr-x
▶ Mac OS X
▶ Unix

Handling Android NDK memory allocation failures in native threads

A native thread in an Android app can keep running after the user leaves a screen, reconnects a sensor or resumes a transfer. During that lifetime, the NDK code may allocate buffers faster than it releases them, retain completed work in a queue or exhaust a 32-bit address space. The visible result might be a null pointer, a failed mmap, std::bad_alloc or an abrupt process death. That makes Android NDK memory allocation failures easy to mislabel as a generic out-of-memory bug.

The Java heap is only one part of an Android process. Native allocations belong to a separate heap, while each thread needs a stack and the process also needs virtual address space for libraries, graphics and graphics buffers. A Java OutOfMemoryError therefore does not explain every native failure, and a healthy Java heap does not prove that native memory is stable. Diagnosis has to follow the native allocation path instead of guessing from ActivityManager or logcat alone.

A useful run keeps the allocation category, requested byte count, ownership and release point together, then separates physical memory pressure from address-space exhaustion. It also records the device, ABI and Android release because allocator behaviour, limits and background-process treatment vary. The aim is to identify which subsystem owns the retained bytes and when they should have gone.

Separate memory exhaustion from other failures

When malloc cannot satisfy a request, C allocation normally returns null and sets an error such as ENOMEM. C++ operator new normally throws std::bad_alloc, while the nothrow form returns null. Do not assume every signal has the same cause: mmap can fail because an address range is unavailable even when RAM appears adequate, and a policy kill can remove the process without any allocation returning an error. Record the exact API and error code before choosing a fix.

Modern Android releases commonly use Scudo, while older devices may use jemalloc. Their accounting and cancellation behaviour differ, but neither makes custom allocation logic a substitute for ownership. A small requested block can fail when a long-lived process has fragmented its heap, retained many equal-sized objects or accumulated stale pages. Thread creation can also fail with EAGAIN when resource limits are reached, while stack exhaustion usually appears as a segmentation fault.

Low-memory killing is another boundary. The system decides which processes are expendable under current memory pressure, so there is no universal free-memory threshold to put in a test. Check the app’s oom_adj and process state around the event, and distinguish a system kill from an allocation error in your own code. A crash report that merges both into one exception will send the investigation in the wrong direction.

Build a diagnostic loop around native allocations

Build a short diagnostic loop around the failing thread. Capture enough data to compare a good run with a bad one, then change one limit at a time. A fixed soak test often exposes growth that ordinary functional tests miss, especially when a queue stays populated across screen changes or service reconnections.

Signals and controls worth capturing

  • Requested bytes, allocation category, thread ID and ownership lifetime

  • Resident size, virtual size, native heap counters and worker stack limits

  • Queue depth, in-flight bytes, cancellation rate and completion latency

  • Device model, ABI, Android release, process state and timestamp

  • Bound the queue and reject work when capacity is reached

  • Reuse buffers only after their previous owner has finished

  • Release native and JNI references on every failure path

  • Cancel queued work when the owning session ends

Android exposes useful counters such as Debug.getNativeHeapAllocatedSize(), while /proc/self/status or smaps_rollup can show process mappings and resident pages on supported releases. Perfetto can add allocation and scheduling events. Treat these as trends: an RSS total that rises while request sizes stay constant may point to retained queues, while rising allocation counts with stable RSS may point to allocator churn.

Make the test observable at the point of failure. Log the requested size, current budget and reason for rejection, but avoid dumping buffer contents, credentials or personal records. A counter that increments when the queue reaches its ceiling is often more useful than another stack trace. It proves that backpressure is working before the allocator is forced to fail.

Repair lifetimes before changing allocators

Repair lifetime before tuning the allocator. Replace ambiguous ownership with RAII objects such as std::unique_ptr and std::vector, and ensure every allocation has a release path when parsing, decoding or JNI work fails midway. Keep buffers scoped to the operation that needs them, return them to a pool once processing completes and avoid references that accidentally survive a callback.

Large allocations deserve a separate budget. Reserve predictable working sets when a stream starts, reject oversized requests early and release whole buffers when a session closes rather than trimming them piecemeal. Continuous consumer workloads, such as those associated with body by inshape, can keep a sensor or profile pipeline active for long periods; steady traffic then exposes retention mistakes that a quick demo never reaches.

Native and Java references can form a retention chain even when the native buffer itself appears correctly freed. A global JNI reference can pin an object and resources reachable from it. Pair acquisition with cleanup, remove global references when a worker finishes and audit callbacks for captured contexts. If work is queued after the Activity is gone, bind that work to an application-scoped coordinator or cancel it explicitly.

Reproduce failures on representative devices

Reproduce on hardware that resembles the Australian audience rather than relying only on a workstation emulator. Australia’s handset market includes capable flagship phones and lower-memory models, so test at least one constrained device with the oldest supported Android release and ABI you ship. Emulators are useful for functional checks, yet their memory behaviour does not reproduce vendor kernels, thermal management or background-process limits.

Make every native build reproducible: pin the NDK revision, CMake configuration, ABI, compiler flags and application commit, then save the exact test data and soak duration. For projects that also exercise a web backend, the workflow described in Docker and database snapshots offers a useful discipline of restoring known states before comparison. The native memory result should be attached to the same recorded build as backend or API fixtures.

Everyday use adds lifecycle churn that a tidy lab session can hide. Engineers in Sydney, Melbourne and Brisbane commonly move between trains, offices and home connections, while prepaid plans and regional 4G or 5G coverage produce frequent reconnects for field teams. Those transitions can restart background work and rebuild buffers. The allocation test should include repeated foreground and background changes, network loss, screen rotation and process restoration instead of assuming one uninterrupted run.

Turn diagnosis into a production response

A production response needs tiers. First stop accepting work, then drain or cancel what can be discarded, release completed buffers and report a recoverable error to the caller. If the process remains above its safe footprint, fail the current feature cleanly or schedule an orderly restart. Restarting is a valid containment tool for a long-running service, but it must be visible in telemetry and paired with a root-cause fix.

For covered Australian organisations, diagnostic telemetry must also respect the Privacy Act 1988 and the Australian Privacy Principles. Keep telemetry minimised, secure it appropriately, disclose its purpose in the app’s privacy information and avoid repurposing it without appropriate consent. Keep user content out of allocation logs, define retention periods and control access to identifiers. These controls protect people while producing cleaner evidence about memory growth.

Make the next release the proof point: select one suspected leak, reproduce it on a constrained Australian-market device, capture the baseline and apply one bounded change at a time. Publish the measured before-and-after footprint with the build details, preserve the diagnostic artefacts and assign an owner for the next soak run. Turn the successful result into a repeatable runbook the whole native team can use.


cat ~/interests.json

KeyValue
editorTerminal-first workflow
osMac OS X / Unix
vcsGit, distributed version control
deployCapistrano, cron automation
graphicsSVG, Adobe Illustrator troubleshooting
networkingIP validation, SSH, VPN

git log --oneline --reverse

2013-10-30

Solving SVG import issues in Adobe Illustrator CS6 and CC

When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.

2013

Solving NDK build issues on OS X

Troubleshooting native development kit compilation problems on Mac OS X.

2013

Programmatically adding PHP generated TypoScript to the backend configuration

Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.

2013

ArgumentError: Could not parse PKey: no start line

Debugging an SSH key parsing error encountered during deployment.

2011-08-04

Validating IP-Addresses in PHP

Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.

2011-07-09

Cocoa: Using NSTrackingArea

A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.


cat ~/contact.txt

github: github.com/x3ro
stackoverflow: x3ro
coderwall: coderwall.com/x3ro
twitter: @x3rames