Skip to content

fix: Fix dangling pointer#1010

Merged
daveallie merged 1 commit intocrosspoint-reader:masterfrom
Uri-Tauber:fix/dangling-pointer-recent-books
Feb 20, 2026
Merged

fix: Fix dangling pointer#1010
daveallie merged 1 commit intocrosspoint-reader:masterfrom
Uri-Tauber:fix/dangling-pointer-recent-books

Conversation

@Uri-Tauber
Copy link
Contributor

Summary

  • What is the goal of this PR? Small fix for bug I found.

Additional Context

  1. RecentBooksActivity::loop() calls onSelectBook(recentBooks[selectorIndex].path) - passing a reference to the path
  2. onSelectBook is onGoToReader which first calls exitActivity()
  3. exitActivity() triggers RecentBooksActivity::onExit() which call recentBooks.clear()
  4. The string reference initialEpubPath is now a dangling reference - the underlying string has been destroyed
  5. When the reference is then used in new ReaderActivity(...), it reads garbage memory
  6. The same issue occurs in HomeActivity at line 200 with the same pattern

The fix is to make a copy of the string in onGoToReader before calling exitActivity(), so the path data persists even after the activity clears its data structures.


AI Usage

Did you use AI tools to help write this code? < YES > Claude found the bug, after I shared with it a serial log.

@Uri-Tauber Uri-Tauber changed the title Fix dangling pointer fix: Fix dangling pointer Feb 19, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 19, 2026

No actionable comments were generated in the recent review. 🎉

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b68bb79 and fde13b7.

📒 Files selected for processing (1)
  • src/main.cpp
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: Levrk
Repo: crosspoint-reader/crosspoint-reader PR: 909
File: src/activities/reader/EpubReaderActivity.cpp:461-461
Timestamp: 2026-02-16T20:43:19.339Z
Learning: In src/activities/reader/EpubReaderActivity.cpp, when using ConfirmationActivity with enterNewActivity(), it's not necessary to call exitActivity() beforehand. The ConfirmationActivity operates as a modal dialog and cleanup is handled via the pendingSubactivityExit flag in the callback lambda. This differs from other activities like EpubReaderChapterSelectionActivity or KOReaderSyncActivity which do require exitActivity() before enterNewActivity().
Learnt from: GavinHigham
Repo: crosspoint-reader/crosspoint-reader PR: 966
File: src/activities/ActivityWithSubactivity.h:20-21
Timestamp: 2026-02-18T15:43:07.515Z
Learning: In the crosspoint-reader activity architecture, when using ActivityWithSubactivity, the currentActivity global variable remains at the top-level activity (e.g., ReaderActivity) even when nested subactivities are active. The supportsOrientation() delegation chain starts from the top-level activity and stops when it reaches a subactivity that overrides the method (e.g., EpubReaderActivity returns true). Deeper nested subactivities (like EpubReaderChapterSelectionActivity or EpubReaderPercentSelectionActivity) do not need to override supportsOrientation() because they never become the currentActivity and the delegation chain doesn't reach them.
Learnt from: Tritlo
Repo: crosspoint-reader/crosspoint-reader PR: 1003
File: src/activities/reader/EpubReaderActivity.cpp:657-674
Timestamp: 2026-02-19T17:46:26.871Z
Learning: In src/activities/reader/EpubReaderActivity.cpp's renderContents() method, when uncached images exist, Phase 1 intentionally calls displayBuffer(forceFullRefresh) to perform a HALF_REFRESH (if needed), while Phase 2 intentionally calls renderer.displayBuffer() directly without forceFullRefresh. This is by design: Phase 1's refresh clears the screen properly to prevent ghosting, so Phase 2 can use a faster refresh mode for better performance. The grayscale anti-aliasing is handled separately after renderContents() via displayGrayBuffer().
📚 Learning: 2026-02-16T20:43:19.339Z
Learnt from: Levrk
Repo: crosspoint-reader/crosspoint-reader PR: 909
File: src/activities/reader/EpubReaderActivity.cpp:461-461
Timestamp: 2026-02-16T20:43:19.339Z
Learning: In src/activities/reader/EpubReaderActivity.cpp, when using ConfirmationActivity with enterNewActivity(), it's not necessary to call exitActivity() beforehand. The ConfirmationActivity operates as a modal dialog and cleanup is handled via the pendingSubactivityExit flag in the callback lambda. This differs from other activities like EpubReaderChapterSelectionActivity or KOReaderSyncActivity which do require exitActivity() before enterNewActivity().

Applied to files:

  • src/main.cpp
📚 Learning: 2026-02-18T15:43:07.515Z
Learnt from: GavinHigham
Repo: crosspoint-reader/crosspoint-reader PR: 966
File: src/activities/ActivityWithSubactivity.h:20-21
Timestamp: 2026-02-18T15:43:07.515Z
Learning: In the crosspoint-reader activity architecture, when using ActivityWithSubactivity, the currentActivity global variable remains at the top-level activity (e.g., ReaderActivity) even when nested subactivities are active. The supportsOrientation() delegation chain starts from the top-level activity and stops when it reaches a subactivity that overrides the method (e.g., EpubReaderActivity returns true). Deeper nested subactivities (like EpubReaderChapterSelectionActivity or EpubReaderPercentSelectionActivity) do not need to override supportsOrientation() because they never become the currentActivity and the delegation chain doesn't reach them.

Applied to files:

  • src/main.cpp
🧬 Code graph analysis (1)
src/main.cpp (1)
src/activities/ActivityWithSubactivity.cpp (4)
  • exitActivity (20-27)
  • exitActivity (20-20)
  • enterNewActivity (29-34)
  • enterNewActivity (29-29)
🔇 Additional comments (1)
src/main.cpp (1)

218-221: Good fix: avoids dangling reference across exitActivity().

Copying the path before exitActivity() safely preserves the string for ReaderActivity construction.


📝 Walkthrough

Walkthrough

In onGoToReader, the code now copies the incoming initialEpubPath into a local std::string before calling exitActivity(), then passes that local copy to the ReaderActivity constructor to avoid potential reference invalidation when exitActivity() destroys the current activity.

Changes

Cohort / File(s) Summary
Reference invalidation fix
src/main.cpp
In onGoToReader, create const std::string bookPath = initialEpubPath; and pass bookPath to ReaderActivity after calling exitActivity(), preventing the original reference from being invalidated.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Suggested reviewers

  • znelson
  • ngxson
🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: Fix dangling pointer' directly and clearly describes the main change: fixing a dangling pointer bug in the code.
Description check ✅ Passed The description comprehensively explains the dangling reference bug, the root cause, the impact, and the fix applied, with clear context about the issue.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@Uri-Tauber
Copy link
Contributor Author

Here’s the serial log that shows the bug in action:

[23:35:11]   Writing frame buffer to RED RAM (48000 bytes)...
[23:35:11]   RED RAM write complete (12 ms)
[23:35:12] [DBG] [RBA] Selected recent book: /Terry Pratchett - Discworld Complete Collection/Pratchett, Terry - [Discworld 17] - Interesting Times (1994, HarperTorch).epub
[23:35:12] [DBG] [ACT] Exiting activity: RecentBooks
[23:35:12] [DBG] [ACT] Entering activity: Reader
[23:35:12] [ERR] [READER] File does not exist: /Terry PratcxV���
[23:35:12] [DBG] [ACT] Exiting activity: Reader
[23:35:12] [DBG] [ACT] Entering activity: Home
[23:35:12]   Transparent image drawn to frame buffer
[23:35:12]   Transparent image drawn to frame buffer

@Uri-Tauber Uri-Tauber force-pushed the fix/dangling-pointer-recent-books branch from b68bb79 to fde13b7 Compare February 19, 2026 22:12
Copy link
Contributor

@ngxson ngxson left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is OK for a quick fix, but I think we must eventually have an ActivityManager to avoid having to pass the function pointer to each activity. We should implement the same idea as Intent on android

The current code is a dangerous delete this because the activity is deleting itself while calling its member (which is onSelectBook in this case)

Call stack:

  • instance.onSelectBook() calls onGoToReader()
  • onGoToReader() calls exitActivity()
  • exitActivity() invokes delete currentActivity
  • currentActivity is the same as instance on step 1 --> literally delete this;

@daveallie daveallie merged commit 63b2643 into crosspoint-reader:master Feb 20, 2026
6 checks passed
@ngxson ngxson mentioned this pull request Feb 20, 2026
5 tasks
@Uri-Tauber Uri-Tauber deleted the fix/dangling-pointer-recent-books branch February 20, 2026 04:52
daveallie pushed a commit that referenced this pull request Feb 20, 2026
## Summary

* **What is the goal of this PR?** Small fix for bug I found.

## Additional Context


1. `RecentBooksActivity::loop()` calls
`onSelectBook(recentBooks[selectorIndex].path)` - passing a
**reference** to the path
  2. `onSelectBook` is `onGoToReader` which first calls `exitActivity()`
3. `exitActivity()` triggers `RecentBooksActivity::onExit()` which call
`recentBooks.clear()`
4. The string reference `initialEpubPath` is now a **dangling
reference** - the underlying string has been destroyed
5. When the reference is then used in `new ReaderActivity(...)`, it
reads garbage memory
6. The same issue occurs in `HomeActivity` at line 200 with the same
pattern

The fix is to make a copy of the string in `onGoToReader` before calling
`exitActivity()`, so the path data persists even after the activity
clears its data structures.

---

### AI Usage

Did you use AI tools to help write this code? _**< YES >**_ Claude found
the bug, after I shared with it a serial log.
lukestein pushed a commit to lukestein/crosspoint-reader that referenced this pull request Feb 20, 2026
## Summary

* **What is the goal of this PR?** Small fix for bug I found.

## Additional Context


1. `RecentBooksActivity::loop()` calls
`onSelectBook(recentBooks[selectorIndex].path)` - passing a
**reference** to the path
  2. `onSelectBook` is `onGoToReader` which first calls `exitActivity()`
3. `exitActivity()` triggers `RecentBooksActivity::onExit()` which call
`recentBooks.clear()`
4. The string reference `initialEpubPath` is now a **dangling
reference** - the underlying string has been destroyed
5. When the reference is then used in `new ReaderActivity(...)`, it
reads garbage memory
6. The same issue occurs in `HomeActivity` at line 200 with the same
pattern

The fix is to make a copy of the string in `onGoToReader` before calling
`exitActivity()`, so the path data persists even after the activity
clears its data structures.

---

### AI Usage

Did you use AI tools to help write this code? _**< YES >**_ Claude found
the bug, after I shared with it a serial log.
ngxson added a commit that referenced this pull request Feb 27, 2026
## Summary

Ref comment:
#1010 (review)

This PR introduces `ActivityManager`, which mirrors the same concept of
Activity in Android, where an activity represents a single screen of the
UI. The manager is responsible for launching activities, and ensuring
that only one activity is active at a time.

Main differences from Android's ActivityManager:
- No concept of Bundle or Intent extras
- No onPause/onResume, since we don't have a concept of background
activities
- onActivityResult is implemented via a callback instead of a separate
method, for simplicity

## Key changes

- Single `renderTask` shared across all activities
- No more sub-activity, we manage them using a stack; Results can be
passed via `startActivityForResult` and `setResult`
- Activity can call `finish()` to destroy themself, but the actual
deletion will be handled by `ActivityManager` to avoid `delete this`
pattern

As a bonus: the manager will automatically call `requestUpdate()` when
returning from another activity

## Example usage

**BEFORE**:

```cpp
// caller
    enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
                                               [this](const bool connected) { onWifiSelectionComplete(connected); }));

// subactivity
  onComplete(true); // will eventually call exitActivity(), which deletes the caller instance (dangerous behavior)
``` 

**AFTER**: (mirrors the `startActivityForResult` and `setResult` from
android)

```cpp
// caller
  startActivityForResult(new NetworkModeSelectionActivity(renderer, mappedInput),
                         [this](const ActivityResult& result) { onNetworkModeSelected(result.selectedNetworkMode); });

// subactivity
  ActivityResult result;
  result.isCancelled = false;
  result.selectedNetworkMode = mode;
  setResult(result);
  finish(); // signals to ActivityManager to go back to last activity AFTER this function returns
```

TODO:
- [x] Reconsider if the `Intent` is really necessary or it should be
removed (note: it's inspired by
[Intent](https://developer.android.com/guide/components/intents-common)
from Android API) ==> I decided to keep this pattern fr clarity
- [x] Verify if behavior is still correct (i.e. back from sub-activity)
- [x] Refactor the `ActivityWithSubactivity` to just simple `Activity`
--> We are using a stack for keeping track of sub-activity now
- [x] Use single task for rendering --> avoid allocating 8KB stack per
activity
- [x] Implement the idea of [Activity
result](https://developer.android.com/training/basics/intents/result)
--> Allow sub-activity like Wifi to report back the status (connected,
failed, etc)

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? **PARTIALLY**, some
repetitive migrations are done by Claude, but I'm the one how ultimately
approve it

---------

Co-authored-by: Zach Nelson <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants