android / android/ndk-samples

Potential issue with standard main loop in NDK samples

Open
#1,094 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
10.5k
Forks
4.3k
PR merge metrics
No merged PRs in 30d

Description

The main loop used in many Android NDK samples follows this standard structure:
```cpp
void android_main(android_app* state)
{
...

while (!state->destroyRequested) {
android_poll_source* source = nullptr;
int result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, (void**)&source);
if (result == ALOOPER_POLL_ERROR)
break;

if (source != nullptr)
source->process(state, source);

// Issue: This code is executed even after state->destroyRequested is set to true
if (g_engine.IsReady())
g_engine.DrawFrame();
}

...
}
```

**Issue:**
`state->destroyRequested` is set to `true` in `source->process(state, source)` when a "destroy" event occurs. However, the code continues executing after `state->destroyRequested` is set which can lead to undefined behavior, e.g. accessing released resources.

**Potential Fix:**
```cpp
android_poll_source* source;
while (ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, reinterpret_cast(&source)) != ALOOPER_POLL_ERROR) {
if (source != nullptr) {
source->process(state, source);

// Exit loop immediately after destroy is requested
if (state->destroyRequested != 0)
break;
}

if (g_engine.IsReady())
g_engine.DrawFrame();
}
```

Contributor guide

Open the contributing guide

Research direction

Locate the Android NDK samples containing the android_main loop and inspect how ALooper_pollOnce, android_poll_source::process, and destroyRequested interact. Reproduce or reason through a destroy event, then update the affected loops so no frame is drawn after destruction and verify the samples still build and handle normal lifecycle events.

Written by the indexing model from the issue text.

Assessment

Tech stack
android, cpp
Domain
mobile-dev
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.