Skip to content

Deleting segments is not handled properly #4304

Closed

Description

@DedeHai

What happened?

When having multiple segments, deleting one of them results in broken segment configuration with one exception: if it is the last segment that is deleted.

To Reproduce Bug

I tested like this on a 16x16 matrix, setting-up 3 overlapping segments:

  • Segment 0: initial segment is 16x16
  • Segment 1: overlapping segment 8x16 (start at x=0)
  • Segment 2: overlapping segment 8x16 (start at x=8)

setup any FX you like, I used "Black Hole" on all three segments
delete the middle segment -> the last segment gets broken and has to be deleted before it can work again

Expected Behavior

deleting a segment should not mess up other segments, it should be properly handled.

Install Method

Binary from WLED.me

What version of WLED?

Not working on 14.4 and 15 B7

Which microcontroller/board are you seeing the problem on?

ESP32-C3

Relevant log/trace output

No response

Anything else?

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. softhack007 commented on Nov 22, 2024

    @softhack007
    Member

    This might be a case of "it was always like this", however would be good to understand the root cause before releasing 0.15.0-RC1

  2. DedeHai commented on Nov 23, 2024

    @DedeHai
    CollaboratorAuthor

    I stumbled upon this when working on the new memory management for the particle system. When deleting the middle segment, there is a particle memory request (which is done when initializing a new FX i.e. call==0) with a segment of nonsensical size of x=0, y=16 which I confirmed is created by deserializeSegment calling the segment setUp() function. So the root cause may be even coming from the UI or incorrect handling of the UI decoding.

  3. netmindz commented on Nov 25, 2024

    @netmindz
    Member

    Sounds like not a blocker for rc1 then

  4. blazoncek commented on Nov 26, 2024

    @blazoncek
    Contributor

    FYI segments are not deleted from memory when user removes them form UI (or using API). Instead they are deactivated.
    This behaviour is the same as it was since 0.10 (stop becomes 0), the difference is that since 0.14 segments are stored in vector and not in fixed size array. This is also where isActive() method comes from.
    If a user later re-activates such segment (using API) no memory intensive operations happen.

    Removing segment when it is deactivated is possible, just remove it from vector and you are done. Be aware that this will trigger copying/moving active segments in memory (from one vector to a new one). Pruning/purging is done if more than half of segments are deactivated to release some memory.

    One possible way to work around the issue may be to manually condense vector by overwriting deactivated segments with still active segments (using move constructor) and then prune remaining inactive segments.

    As for non-working third segment from example above, only debugging can show what's happening with it. I have the feeling that root issue lies in UI rather than segments themselves. But I may be wrong.

  5. added this to the 0.16.0 candidate milestone on Nov 27, 2024
  6. added
    backburner
    on Nov 28, 2024
  7. DedeHai commented on Jul 24, 2025

    @DedeHai
    CollaboratorAuthor

    FYI: this is fixed in 0.16

  8. added
    fixed in source
    and removed
    fixed in source
    on Mar 9, 2026
  9. softhack007 commented on Mar 9, 2026

    @softhack007
    Member

    maintainers: I think this is still a problem, at least if the "delete preset" call is overlapping with another ongoing preset modification - for example when first updating a preset from the UI (keep "overwrite with state" disabled), and then quickly after that delete any other preset.

    WLED/wled00/presets.cpp

    Lines 280 to 285 in 53d6c4b

    void deletePreset(byte index) {
    StaticJsonDocument<24> empty;
    writeObjectToFileUsingId(getPresetsFileName(), index, &empty);
    presetsModifiedTime = toki.second(); //unix time
    updateFSInfo();
    }

    WLED/wled00/json.cpp

    Lines 499 to 501 in 53d6c4b

    ps = root[F("pdel")]; //deletion
    if (ps > 0 && ps < 251) deletePreset(ps);

  10. softhack007 commented on Mar 9, 2026

    @softhack007
    Member

    @coderabbitai please check if the scenario described in this report - presets or segments corruption due to parallel changes from several tasks - is still possible in the main branch. Consider that there are two possible paths - depending on UI options used when creating or updating a preset. The expected behaviour should be that all file writes to presets.json are serialized asynchronously via the main loopTask. Please also verify if the existing JSON buffer locking mechanism can effectively prevent presets corruption due to parallel writing.

  11. softhack007 commented on Mar 9, 2026

    @softhack007
    Member

    oopsie - mixed things up - this issue is about deleting segments, not about the preset deletion bug 😅

  12. coderabbitai commented on Mar 9, 2026

    @coderabbitai
    Contributor

    Coding Plan

    Summary

    • Remove the restrictive threshold condition for purgeSegments() so deleted segments are always compacted out of the vector
    • Fix the memory leak in the Segment destructor by freeing the Transition pointer
    • Both fixes are minimal, surgical changes that address specific bugs without introducing new abstractions or refactoring existing patterns
    Design Choices
    Design Choice 1: Should `purgeSegments()` be called unconditionally or only when deletions occurred?

    Options Considered:

    1. Call purgeSegments() unconditionally after processing the segment array
    2. Call purgeSegments() only when at least one segment was deleted (check deleted > 0)
    3. Lower the threshold but keep some batching logic

    Chosen Option: 2

    Rationale: The current threshold (>3 segments AND >=50% deleted) was likely added for performance optimization to avoid frequent vector reallocations. However, correctness must take priority. Option 2: Call purgeSegments() when deleted > 0. This ensures holes are always cleaned up while avoiding unnecessary calls when no deletions occurred, maintaining the intent of the original optimization while fixing the bug.

    💡 User Tips

    Regenerate the plan with different choices with @coderabbitai <feedback>.

    Implementation Steps

    Phase 1: Fix Segment Deletion Handling

    This phase addresses the core bug by ensuring inactive segments are always removed from the vector after deletion, preventing positional mismatches.

    Remove Restrictive Threshold for purgeSegments()

    Replace the overly restrictive threshold condition that prevents proper cleanup of deleted segments.

    • In wled00/json.cpp, locate the purgeSegments() call after the segment array processing loop (around line 487)
    • Change the condition from if (strip.getSegmentsNum() > 3 && deleted >= strip.getSegmentsNum()/2U) to simply if (deleted) (or if (deleted > 0))
    • This ensures any deletion triggers cleanup, not just batch deletions of half or more segments
    • The call is already protected by strip.suspend() / strip.resume() wrapper, so service() safety is maintained
    🤖 Prompt for AI agents
    Fix the core segment deletion bug in `wled00/json.cpp` by replacing the overly
    restrictive threshold that prevents proper cleanup of deleted segments.
    
    - Locate the `purgeSegments()` call after the segment array processing loop
    (around line 487)
    - Replace the condition `if (strip.getSegmentsNum() > 3 && deleted >=
    strip.getSegmentsNum()/2U)` with `if (deleted)` (or equivalently `if (deleted >
    0)`)
    - This ensures that any deletion — not just batch deletions of half or more
    segments — triggers a cleanup of inactive ("hole") segments from the vector
    - No other changes are needed; the call is already safely wrapped by
    `strip.suspend()` / `strip.resume()`
    

    Phase 2: Fix Segment Destructor Memory Leak

    This phase addresses a secondary bug discovered during analysis - the Segment destructor does not free the Transition pointer, causing memory leaks when segments with active transitions are destroyed.

    Add Transition Cleanup to Destructor

    Ensure the _t (Transition) pointer is properly freed when a Segment is destroyed.

    • In wled00/FX.h, locate the ~Segment() destructor (around line 618)
    • Add a call to free the transition before existing cleanup: if (_t) { delete _t; _t = nullptr; } or call stopTransition() if accessible from the destructor context
    • This must occur before deallocateData() and p_free(pixels) to maintain proper cleanup order
    • Note: stopTransition() is a public method that does delete _t; _t = nullptr;, so it can be called directly if preferred for consistency
    🤖 Prompt for AI agents
    Fix the memory leak in the `Segment` destructor in `wled00/FX.h` by ensuring the
    `_t` (Transition) pointer is freed when a Segment is destroyed.
    
    - Locate the `~Segment()` destructor (around line 618)
    - At the beginning of the destructor body, before `deallocateData()` and
    `p_free(pixels)`, add transition cleanup:
      - Either add `if (_t) { delete _t; _t = nullptr; }` directly
    - Or call `stopTransition()` (a public method that performs `delete _t; _t =
    nullptr;`) for consistency with existing patterns
    - Ensure this cleanup occurs before any other resource deallocation in the
    destructor to maintain proper cleanup order
    
    Research

    WLED stores segments in a std::vector<Segment> within the WS2812FX class. Segment deletion is implemented as a "soft delete" - setting stop=0 marks the segment inactive but leaves it in the vector. The purgeSegments() function removes these inactive entries, but is only called when more than 3 segments exist AND at least half are deleted in one batch. This threshold causes "holes" to persist in common scenarios, leading to state corruption when the UI reflects segment data back to the controller. Additionally, the Segment destructor has a memory leak - it does not free the _t (Transition) pointer.


    🚀 Next Steps

    🤖 All AI agent prompts combined
    Task: 1
    
    Fix the core segment deletion bug in `wled00/json.cpp` by replacing the overly
    restrictive threshold that prevents proper cleanup of deleted segments.
    
    - Locate the `purgeSegments()` call after the segment array processing loop
    (around line 487)
    - Replace the condition `if (strip.getSegmentsNum() > 3 && deleted >=
    strip.getSegmentsNum()/2U)` with `if (deleted)` (or equivalently `if (deleted >
    0)`)
    - This ensures that any deletion — not just batch deletions of half or more
    segments — triggers a cleanup of inactive ("hole") segments from the vector
    - No other changes are needed; the call is already safely wrapped by
    `strip.suspend()` / `strip.resume()`
    ===============================================================================
    
    Task: 2
    
    Fix the memory leak in the `Segment` destructor in `wled00/FX.h` by ensuring the
    `_t` (Transition) pointer is freed when a Segment is destroyed.
    
    - Locate the `~Segment()` destructor (around line 618)
    - At the beginning of the destructor body, before `deallocateData()` and
    `p_free(pixels)`, add transition cleanup:
      - Either add `if (_t) { delete _t; _t = nullptr; }` directly
    - Or call `stopTransition()` (a public method that performs `delete _t; _t =
    nullptr;`) for consistency with existing patterns
    - Ensure this cleanup occurs before any other resource deallocation in the
    destructor to maintain proper cleanup order
    
    💡 Iterate on the plan with: @coderabbitai <feedback>
    Example Feedback
    - `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2.
    - `@coderabbitai` For design choice 1 go ahead with option 3 and replan.
    

    💬 Have feedback or questions? Drop into our discord!

  13. softhack007 commented on Mar 9, 2026

    @softhack007
    Member

    @coderabbitai please review and inspect the current source code. According to this comment the problem should be solved.

  14. 14 remaining items

  15. softhack007 commented on Jun 17, 2026

    @softhack007
    Member

    The destructor definitely HAS TO delete(_t), which it currently does not.

    @DedeHai it looks like the code was removed somewhere between 0.15.x and 16.0 ... any idea why?

    WLED/wled00/FX.h

    Lines 509 to 511 in 5dc9f0c

    if (name) { delete[] name; name = nullptr; }
    stopTransition();
    deallocateData();

    @coderabbitai please trace through the commit history of main, and find the commit which removed the stopTransition(); call in the ~segment destructor. Also check if there is a PR or issue ticket or other justification that can explain this removal.

  16. coderabbitai commented on Jun 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    # Find the commit that removed stopTransition from the destructor area in FX.h
    # Use pickaxe to find commits that changed the occurrence count of "stopTransition" in FX.h
    git log --oneline -S "stopTransition" -- wled00/FX.h | head -20
    
    echo ""
    echo "=== Also try looking at destructor area changes ==="
    git log --oneline --follow -- wled00/FX.h | head -30

    Length of output: 496


    🏁 Script executed:

    #!/bin/bash
    # Show what the destructor looked like around the reference commit and then diff forward
    echo "=== FX.h destructor at reference commit 5dc9f0c ==="
    git show 5dc9f0c87de34b99aeb8493c2d7e5998a1273aca:wled00/FX.h | grep -n -A 15 "~Segment"
    
    echo ""
    echo "=== Commits that touched the destructor area (pickaxe on ~Segment) ==="
    git log --oneline -S "~Segment" -- wled00/FX.h | head -20
    
    echo ""
    echo "=== All commits between reference commit and HEAD that touched FX.h ==="
    git log --oneline 5dc9f0c87de34b99aeb8493c2d7e5998a1273aca..HEAD -- wled00/FX.h | head -40

    Length of output: 701


    🏁 Script executed:

    #!/bin/bash
    # Show the destructor at the reference commit (fast, single object fetch)
    git show 5dc9f0c87de34b99aeb8493c2d7e5998a1273aca:wled00/FX.h 2>/dev/null | grep -n "stopTransition\|~Segment\|deallocateData\|p_free\|pixels" | head -30

    Length of output: 1631


    🏁 Script executed:

    #!/bin/bash
    # Use GitHub API to search for recent PRs/commits that modified FX.h
    # Search merged PRs mentioning FX.h or Segment destructor or stopTransition
    gh api "repos/wled/WLED/commits?path=wled00/FX.h&per_page=30" --jq '.[].sha + " " + .[].commit.message[0:80]' 2>/dev/null | head -30

    Length of output: 1554


    🏁 Script executed:

    #!/bin/bash
    # Search GitHub for issues/PRs mentioning stopTransition removal or Segment destructor
    gh search prs --repo wled/WLED --state merged "stopTransition destructor" --json number,title,url --limit 10 2>/dev/null
    
    echo ""
    gh search prs --repo wled/WLED --state merged "Segment destructor" --json number,title,url --limit 10 2>/dev/null
    
    echo ""
    gh search issues --repo wled/WLED "stopTransition destructor" --json number,title,url --limit 10 2>/dev/null

    Length of output: 510


    🏁 Script executed:

    #!/bin/bash
    # Check current destructor in main
    echo "=== Current ~Segment destructor ==="
    rg -n "~Segment\|stopTransition\|deallocateData\|p_free.*pixels\|pixels.*free" wled00/FX.h | head -20
    
    echo ""
    echo "=== PR `#5675` files changed - check if it touched destructor ==="
    gh pr view 5675 --repo wled/WLED --json title,body,mergedAt | jq '{title,mergedAt,body:.body[0:300]}'
    
    echo ""
    # Get more pages of commits on FX.h
    echo "=== More commits on FX.h (pages 2-4) ==="
    gh api "repos/wled/WLED/commits?path=wled00/FX.h&per_page=10&page=2" --jq '.[].sha[0:10] + " " + .[].commit.message[0:80]' 2>/dev/null
    echo "---page3---"
    gh api "repos/wled/WLED/commits?path=wled00/FX.h&per_page=10&page=3" --jq '.[].sha[0:10] + " " + .[].commit.message[0:80]' 2>/dev/null
    echo "---page4---"
    gh api "repos/wled/WLED/commits?path=wled00/FX.h&per_page=10&page=4" --jq '.[].sha[0:10] + " " + .[].commit.message[0:80]' 2>/dev/null

    Length of output: 25250


    🏁 Script executed:

    #!/bin/bash
    # Look at each commit sha from first page and check if it removed stopTransition
    # The commits returned were all from PR `#5675` - let's look at what changed in that PR for FX.h destructor
    gh api "repos/wled/WLED/pulls/5675/files" --jq '.[] | select(.filename == "wled00/FX.h") | .patch' 2>/dev/null | head -100

    Length of output: 982


    🏁 Script executed:

    #!/bin/bash
    echo "=== Check if ~Segment moved to FX_fcn.cpp ==="
    rg -n "~Segment\|Segment::~" wled00/FX_fcn.cpp | head -20
    rg -n "~Segment" wled00/FX.h | head -10
    
    echo ""
    echo "=== PR `#4658` - files changed ==="
    gh pr view 4658 --repo wled/WLED --json title,mergedAt,body | jq '{title,mergedAt,body:.body[0:500]}'
    
    echo ""
    echo "=== PR `#4658` diff for FX.h destructor area ==="
    gh api "repos/wled/WLED/pulls/4658/files" --jq '.[] | select(.filename == "wled00/FX.h") | .patch' 2>/dev/null | grep -A 20 -B 5 "stopTransition\|~Segment\|destructor\|deallocateData" | head -80
    
    echo ""
    echo "=== 'Bugfix for gif playback and segment destruction' commit - find it ==="
    gh api "repos/wled/WLED/commits?path=wled00/FX.h&per_page=50&page=2" --jq '.[] | select(.commit.message | contains("gif")) | {sha: .sha[0:10], msg: .commit.message[0:120]}' 2>/dev/null

    Length of output: 6132


    🏁 Script executed:

    #!/bin/bash
    # Search for the specific commit about gif/segment destruction
    gh api "repos/wled/WLED/search/commits?q=gif+segment+destruction+repo:wled/WLED" 2>/dev/null | head -5 || true
    
    # Try searching PRs with "gif" and "segment destruction"
    gh search prs --repo wled/WLED "gif segment destruction" --json number,title,url,mergedAt --limit 5 2>/dev/null
    
    echo ""
    # Look at the "implement recommendations" commits from PR `#4658` context
    # The sha repeated 10 times is bb6114e8aa - let's check that commit directly
    echo "=== Check commit bb6114e8aa ==="
    gh api "repos/wled/WLED/commits/bb6114e8aa" --jq '{sha: .sha[0:10], message: .commit.message[0:300]}' 2>/dev/null
    
    echo ""
    echo "=== Check if PR `#4658` patch contains stopTransition removal ==="
    gh api "repos/wled/WLED/pulls/4658/files?per_page=100" --jq '.[].filename' 2>/dev/null | grep -i "FX"

    Length of output: 1241



    @softhack007 — Found it. The stopTransition() call was removed in PR #4658 ("Segment layers and better effect transitions (blending)"), merged 2025-06-01.

    The diff for the destructor in that PR:

         ~Segment() {
           `#ifdef` WLED_DEBUG
    -      //Serial.printf("-- Destroying segment: %p", this);
    +      DEBUGFX_PRINTF_P(PSTR("-- Destroying segment: %p [%d,%d:%d,%d]"), ...);
    +      DEBUGFX_PRINTF_P(PSTR(" T[%p]"), _t);   // ← _t logged but NOT freed
    +      DEBUGFX_PRINTLN();
           `#endif`
    -      if (name) { free(name); name = nullptr; }
    -      stopTransition();        // ← REMOVED HERE
    +      clearName();
           deallocateData();
    +      d_free(pixels);          // ← new pixel buffer free added
         }

    There is no explicit justification for the removal in the PR description or in any linked issue. It appears to be an accidental omission during the refactoring of the destructor: free(name) was replaced with clearName() and d_free(pixels) was added for the new pixel buffer, but stopTransition() was simply dropped in the process. Ironically, the new debug block even prints _t (the transition pointer), showing the author was aware of it — yet the free was not carried forward.

    Conclusion: The removal was unintentional. Adding stopTransition(); back to the destructor (before deallocateData()) is the correct fix, with no risk of double-free since stopTransition() is guarded by if (_t != nullptr).


    ✏️ Learnings added
    Learnt from: softhack007
    URL: https://github.com/wled/WLED/issues/4304
    
    Timestamp: 2026-06-17T12:03:14.826Z
    Learning: In WLED's `Segment` destructor (`wled00/FX.h`), `stopTransition()` was accidentally removed in PR `#4658` ("Segment layers and better effect transitions", merged 2025-06-01) during a refactoring that replaced `free(name)` with `clearName()` and added `d_free(pixels)`. The fix is to add `stopTransition()` back before `deallocateData()` in the destructor. This is safe because `stopTransition()` is internally guarded (`if (_t != nullptr)`).
    

    Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

  17. softhack007 commented on Jun 17, 2026

    @softhack007
    Member

    The stopTransition() call was removed in PR #4658 ("Segment layers and better effect transitions (blending)"),

    The big "change everything" PR 👀 . I agree it was likely an accident to remove stopTransition();

  18. softhack007 commented on Jun 17, 2026

    @softhack007
    Member

    the destructor of _t also deletes _oldSegment if it exists.

    @coderabbitai please double-check if its safe to add stopTransition(); back to the destructor (before deallocateData()). Is it possible that _oldSegment could have a transition attached to it? If yes, can we exclude that calling ~Transition() may lead to a loop? Please check the possible WLED control flows that can be involved into such a scenario.

  19. coderabbitai commented on Jun 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    echo "=== Transition struct/class definition ==="
    rg -n "struct Transition\|class Transition" wled00/FX.h -A 40
    
    echo ""
    echo "=== stopTransition() implementation ==="
    rg -n "stopTransition" wled00/FX.h -A 10 -B 2
    rg -n "stopTransition" wled00/FX_fcn.cpp -A 10 -B 2
    
    echo ""
    echo "=== _oldSegment: type, where allocated, where freed ==="
    rg -n "_oldSegment" wled00/FX.h -C 5
    rg -n "_oldSegment" wled00/FX_fcn.cpp -C 5
    
    echo ""
    echo "=== Transition destructor (if any) ==="
    rg -n "~Transition" wled00/FX.h -C 10
    rg -n "~Transition" wled00/FX_fcn.cpp -C 10
    
    echo ""
    echo "=== startTransition() - how _t is created and _oldSegment populated ==="
    rg -n "startTransition" wled00/FX_fcn.cpp -A 30 -B 2
    
    echo ""
    echo "=== Does _oldSegment itself have a _t member? (is it a full Segment copy?) ==="
    rg -n "oldSeg\|_oldSeg\|old_seg" wled00/FX.h -C 3
    rg -n "oldSeg\|_oldSeg\|old_seg" wled00/FX_fcn.cpp -C 3
    
    echo ""
    echo "=== Full Segment struct member _t declaration ==="
    rg -n "Transition\s*\*\s*_t\|_t\s*=\s*nullptr\|Transition\* _t" wled00/FX.h -C 2

    Length of output: 20453


    🏁 Script executed:

    #!/bin/bash
    echo "=== Segment copy constructor (search broadly) ==="
    rg -n "Segment\s*\(const Segment\|Segment\s*\(Segment const\|Segment\s*\(const Segment &\|copy constructor" wled00/FX.h -A 20 -B 2
    
    echo ""
    echo "=== All constructors in Segment class ==="
    sed -n '50,200p' wled00/FX.h
    
    echo ""
    echo "=== Move constructor explicitly? ==="
    rg -n "Segment\s*\(Segment\s*&&" wled00/FX.h -A 15
    
    echo ""
    echo "=== Lines around startTransition's new Segment(*this) (lines 315-335) ==="
    sed -n '285,340p' wled00/FX_fcn.cpp
    
    echo ""
    echo "=== In old commit 5dc9f0c: what did startTransition look like? ==="
    git show 5dc9f0c87de34b99aeb8493c2d7e5998a1273aca:wled00/FX_fcn.cpp 2>/dev/null | grep -n "startTransition\|_oldSegment\|_t = new" | head -30
    
    echo ""
    echo "=== In old commit 5dc9f0c: what did the copy constructor / copy assignment look like? ==="
    git show 5dc9f0c87de34b99aeb8493c2d7e5998a1273aca:wled00/FX.h 2>/dev/null | grep -n "Segment\s*(const\|Segment\s*(Segment\|memcpy\|_t = nullptr\|stopTransition" | head -30

    Length of output: 12317



    @softhack007 — This is not safe as a naive one-liner addition. Here is the full analysis:


    Why the double-free loop exists

    The danger comes from the order of operations in startTransition() (FX_fcn.cpp):

    _t = new(std::nothrow) Transition(dur);    // line 316 — _t is NOW set on *this
    // ...
    if (segmentCopy) _t->_oldSegment = new(std::nothrow) Segment(*this);  // line 325 — copy made AFTER _t is set

    new Segment(*this) on line 325 copies *this — including its already-non-null _t pointer. Because there is no longer an explicit copy constructor in the current code (the old Segment(const Segment &orig) was removed in PR #4658), the compiler generates a default member-wise copy. After this line:

    _oldSegment->_t  ==  this->_t   (same pointer, same Transition object)
    

    If stopTransition() is naively added to ~Segment(), the destruction chain becomes:

    ~Segment() (parent)
      → stopTransition()
        → delete _t                       ← Transition freed here
          → ~Transition()
            → delete _oldSegment
              → ~Segment() (on _oldSegment)
                → stopTransition()
                  → delete _t             ← SAME pointer, already freed → double-free crash
    

    This is the same path for both the "new transition" path (line 316/325) and the "already in transition" path (line 299–310).


    The old code was safe — but for a different reason

    In the old code (commit 5dc9f0c, pre-PR #4658), startTransition() did not create _oldSegment at all. It simply allocated _t = new Transition(dur) with no segment copy. The explicit copy constructor Segment(const Segment &orig) that was declared (line 499 in old code) handled _t correctly in that simpler world. When PR #4658 introduced _oldSegment as a full segment copy inside Transition, the explicit copy constructor was removed and the destructor cleanup was lost — two changes that together create the bug.


    The correct fix requires two changes

    Step 1: Null out _oldSegment->_t immediately after creating the copy, in startTransition(). This prevents _oldSegment from ever thinking it owns the Transition:

    // startTransition(), line 325 area
    if (segmentCopy) {
      _t->_oldSegment = new(std::nothrow) Segment(*this);
      if (_t->_oldSegment) {
        _t->_oldSegment->_t = nullptr;  // _oldSegment does not own _t; prevent double-free in ~Segment()
        // ... existing palette/color fixup ...
      }
    }

    The same null assignment is needed in the "already in transition" copy path (line 301).

    Alternatively (equivalent safety), null it in ~Transition() before calling delete _oldSegment:

    ~Transition() {
      if (_oldSegment) {
        _oldSegment->_t = nullptr;  // _t is owned by the parent Segment, not this copy
        delete _oldSegment;
      }
    }

    Step 2 (only after Step 1): Add stopTransition() back to ~Segment():

    ~Segment() {
      // ...debug prints...
      clearName();
      stopTransition();   // safe now because _oldSegment->_t is always nullptr
      // ...gif cleanup...
      deallocateData();
      p_free(pixels);
    }

    Summary

    Question Answer
    Is naively adding stopTransition() to ~Segment() safe? ❌ No — double-free crash via _oldSegment->_t
    Can _oldSegment have a _t attached? ✅ Yes — because the copy is made after _t is set, and no copy constructor nullifies it
    Does calling ~Transition() lead to a loop? ✅ Yes — exactly as described above
    What is the correct fix? Null _oldSegment->_t after copy in startTransition() (or in ~Transition()), then add stopTransition() to destructor

    🐇 🔍

  20. DedeHai commented on Jun 17, 2026

    @DedeHai
    CollaboratorAuthor

    good call, I forgot about the _t in _oldSegment and the rabbit is spot on for once ;)

  21. softhack007 commented on Jun 17, 2026

    @softhack007
    Member

    Step 1: Null out _oldSegment->_t immediately after creating the copy, in startTransition(). This prevents _oldSegment from ever thinking it owns the Transition:

    @coderabbitai i'm still unsure if the pointer copy in _oldSegment->_t is needed (feature) or not (bug). Does the WLED transition logic rely on this second pointer copy? Is it even accessed/evaluated? I think we don't support transitions inside transitions?

  22. coderabbitai commented on Jun 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    echo "=== All uses of _oldSegment in FX_fcn.cpp ==="
    rg -n "_oldSegment" wled00/FX_fcn.cpp -C 4
    
    echo ""
    echo "=== All uses of _oldSegment in FX.h ==="
    rg -n "_oldSegment" wled00/FX.h -C 4
    
    echo ""
    echo "=== All uses of _oldSegment everywhere ==="
    rg -rn "_oldSegment" wled00/ -C 3
    
    echo ""
    echo "=== Does any transition rendering code dereference _oldSegment->_t? ==="
    rg -rn "_oldSegment.*->.*_t\|_oldSegment.*\._t\|->_t" wled00/ -C 3
    
    echo ""
    echo "=== Transition blending: how is _oldSegment used during getPixelColor / blend ==="
    rg -n "getPixelColor\|blendPixel\|getPixels\|_oldSeg\|oldSeg" wled00/FX_fcn.cpp -C 5 | head -100
    
    echo ""
    echo "=== startTransition: full function (lines 285-360 approx) ==="
    sed -n '280,370p' wled00/FX_fcn.cpp
    
    echo ""
    echo "=== Transition struct definition again - all members ==="
    rg -n "struct Transition\|class Transition" wled00/FX.h -A 50

    Length of output: 13613



    @softhack007 — The answer is clear: _oldSegment->_t is never accessed anywhere and is purely a spurious artifact of the shallow memberwise copy.

    Evidence

    The search for any code that dereferences ->_t on _oldSegment returned zero results. Looking at every place _oldSegment is actually used:

    Location What it does with _oldSegment
    startTransition() Sets palette, colors[], checks isActive()
    stopTransition() Only prints its address in a debug message
    ~Transition() delete _oldSegment (frees the copy)
    getOldSegment() Returns the pointer to callers for pixel blending
    Callers of getOldSegment() Read palette, colors, pixels — never _t

    The _t inside _oldSegment is never read or written after the copy is made. It only exists because new Segment(*this) is a memberwise copy and _t is one of the members. This is a bug (unintended shared pointer), not a feature.

    The clean fix — null it in ~Transition()

    Since both copy sites in startTransition() (lines 301 and 325) create the same problem, the single-location fix is in ~Transition():

    ~Transition() {
      if (_oldSegment) {
        _oldSegment->_t = nullptr;  // prevent double-free: _t is owned by the parent Segment, not this copy
        delete _oldSegment;
      }
    }

    This is safe and complete: _oldSegment->_t is never used, so nulling it before deletion has no functional effect — it only breaks the shared-pointer link before ~Segment() fires on the copy.

    After this one-line addition to ~Transition(), it becomes safe to add stopTransition() back to ~Segment() with no risk of recursion or double-free.


    ✏️ Learnings added
    Learnt from: softhack007
    URL: https://github.com/wled/WLED/issues/4304
    
    Timestamp: 2026-06-17T13:28:14.152Z
    Learning: In WLED's `Transition` struct (`wled00/FX.h`), `_oldSegment->_t` is never accessed in any rendering or blending code path. It is a spurious shallow-copy artifact created when `new Segment(*this)` is called in `startTransition()` after `_t` has already been set on the parent segment. The `~Transition()` destructor must null out `_oldSegment->_t` before calling `delete _oldSegment` to break the shared-pointer link and prevent a double-free crash if `stopTransition()` is ever called from `~Segment()`. The fix is: add `_oldSegment->_t = nullptr;` immediately before `delete _oldSegment` in `~Transition()`.
    

    Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

  23. softhack007 commented on Jun 17, 2026

    @softhack007
    Member

    p_free(pixels);

    @coderabbitai is _oldSegment using a copy of the pixels array pointer, or will it always have its own pixels?

  24. coderabbitai commented on Jun 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    echo "=== pixels member in Segment ==="
    rg -n "pixels" wled00/FX.h -C 3 | head -60
    
    echo ""
    echo "=== startTransition: full function, focus on pixels and _oldSegment ==="
    sed -n '280,380p' wled00/FX_fcn.cpp
    
    echo ""
    echo "=== pixels allocation: where is it set / p_alloc'd ==="
    rg -n "pixels\s*=" wled00/FX_fcn.cpp -C 3 | head -80
    
    echo ""
    echo "=== p_free(pixels) and p_alloc.*pixels usages ==="
    rg -n "p_free.*pixels\|p_alloc.*pixels\|pixels.*p_alloc\|pixels.*p_free" wled00/ -C 3
    
    echo ""
    echo "=== getPixels / getReadablePixels - where _oldSegment->pixels is accessed ==="
    rg -n "getPixels\|getReadablePixels\|->pixels\|\\.pixels" wled00/FX_fcn.cpp -C 3 | head -60
    
    echo ""
    echo "=== FX.h line 615-650 (destructor and nearby context) ==="
    sed -n '610,660p' wled00/FX.h
    
    echo ""
    echo "=== After _oldSegment copy in startTransition - is pixels zeroed? ==="
    sed -n '295,360p' wled00/FX_fcn.cpp

    Length of output: 18523



    @softhack007 — _oldSegment always has its own independently allocated pixels buffer — it is a deep copy, never a shared pointer.

    The copy constructor in FX_fcn.cpp makes this explicit:

    // copy constructor body (FX_fcn.cpp ~line 64)
    name    = nullptr;
    data    = nullptr;
    _dataLen = 0;
    pixels  = nullptr;                           // ← start with null
    if (!stop) return;
    if (orig.pixels) {
      pixels = static_cast<uint32_t*>(           // ← allocate NEW buffer
        allocate_buffer(orig.length() * sizeof(uint32_t), ...));
      if (pixels)
        memcpy(pixels, orig.pixels, sizeof(uint32_t) * orig.length()); // ← deep copy
    }

    Every path that creates a Segment copy (new Segment(*this) in startTransition()) goes through this constructor, which immediately nulls pixels and then allocates a fresh buffer. When ~Transition() eventually calls delete _oldSegment, the p_free(pixels) in ~Segment() frees the copy's own allocation — completely independent from the parent segment's pixels.

    So to summarize the destructor safety picture:

    Resource in _oldSegment Shared with parent? Double-free risk?
    pixels ❌ No — deep copy, own allocation ✅ Safe
    name ❌ No — deep copy ✅ Safe
    data ❌ No — deep copy ✅ Safe
    _t ⚠️ Yes — shallow copy of pointer (see previous comments) ❌ Needs _oldSegment->_t = nullptr fix first

    The conclusion from the thread still holds: the two-step fix (_oldSegment->_t = nullptr in ~Transition(), then stopTransition() in ~Segment()) is the correct and complete approach, and pixels is not an additional concern.

  25. softhack007 commented on Jun 17, 2026

    @softhack007
    Member

    @coderabbitai your two statements about the segment copy constructor (explicit / implicit) seem contradicting. please clarify.

    #4304 (comment)

    The old code was safe — but for a different reason

    In the old code (commit 5dc9f0c, pre-PR #4658), startTransition() did not create _oldSegment at all. It simply allocated _t = new Transition(dur) with no segment copy. The explicit copy constructor Segment(const Segment &orig) that was declared (line 499 in old code) handled _t correctly in that simpler world. When PR #4658 introduced _oldSegment as a full segment copy inside Transition, the explicit copy constructor was removed and the destructor cleanup was lost — two changes that together create the bug

    #4304 (comment)

    Every path that creates a Segment copy (new Segment(*this) in startTransition()) goes through this constructor, which immediately nulls pixels and then allocates a fresh buffer. When ~Transition() eventually calls delete _oldSegment, the p_free(pixels) in ~Segment() frees the copy's own allocation — completely independent from the parent segment's pixels.

  26. coderabbitai commented on Jun 17, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    echo "=== Segment copy constructor in FX_fcn.cpp ==="
    rg -n "Segment::Segment\|Segment(const Segment\|Segment(Segment const" wled00/FX_fcn.cpp -A 50 | head -80
    
    echo ""
    echo "=== Copy constructor declaration in FX.h ==="
    rg -n "Segment(const Segment\|copy constructor\|Segment(const Seg" wled00/FX.h -C 3
    
    echo ""
    echo "=== FX_fcn.cpp lines 55-120 (copy constructor area) ==="
    sed -n '55,125p' wled00/FX_fcn.cpp
    
    echo ""
    echo "=== Does the copy constructor null _t? ==="
    rg -n "_t\s*=\s*nullptr\|_t = nullptr" wled00/FX_fcn.cpp -C 5

    Length of output: 4334



    @softhack007 — Apologies for the confusion. My earlier statement was simply wrong, and here is the clarification:

    What's actually in the current main branch

    The explicit copy constructor was not removed — it exists in FX_fcn.cpp and already handles _t correctly:

    Segment::Segment(const Segment &orig) {
      memcpy((void*)this, (void*)&orig, sizeof(Segment));
      _t   = nullptr; // copied segment cannot be in transition  ← nulled immediately
      name = nullptr;
      data = nullptr;
      _dataLen = 0;
      pixels = nullptr;
      // ... deep-copies pixels, name, data ...
    }

    _t is set to nullptr right after the memcpy. This means _oldSegment->_t is always nullptr after new Segment(*this) in startTransition(). The double-free scenario I described earlier was based on a false premise (that the copy constructor was implicit/memberwise).

    Correction to my previous recommendations

    Earlier claim Correct?
    "The explicit copy constructor was removed in PR #4658" ❌ Wrong — it exists in FX_fcn.cpp
    "The double-free loop is possible via _oldSegment->_t" ❌ Wrong — copy constructor nulls _t
    "You need _oldSegment->_t = nullptr in ~Transition() first" ❌ Unnecessary

    The actual fix required

    Just one change — add stopTransition() back to ~Segment() before deallocateData():

    ~Segment() {
      // ...debug prints...
      clearName();
      stopTransition();   // safe: copy constructor already nulls _t in any Segment copy
      // ...gif cleanup...
      deallocateData();
      p_free(pixels);
    }

    No changes to ~Transition() or startTransition() are needed. The copy constructor already makes _oldSegment->_t == nullptr invariant, so there is no recursion or double-free risk.

    🐇 straightens ears sheepishly


    ✏️ Learnings added
    Learnt from: softhack007
    URL: https://github.com/wled/WLED/issues/4304
    
    Timestamp: 2026-06-17T14:10:05.283Z
    Learning: In WLED's `Segment` copy constructor (`wled00/FX_fcn.cpp`), `_t` is explicitly set to `nullptr` immediately after the `memcpy` (with comment "copied segment cannot be in transition"). This means `_oldSegment->_t` created by `new Segment(*this)` in `startTransition()` is always `nullptr`. Therefore, adding `stopTransition()` back to `~Segment()` (before `deallocateData()`) is safe without any changes to `~Transition()` or `startTransition()`. The fix is a single one-line addition to the destructor.
    

    Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

  27. DedeHai commented on Jun 17, 2026

    @DedeHai
    CollaboratorAuthor

    @softhack007 I will check which of the rabbits statements is right, I am not sure the code-path it thinks is taken will always be taken. It should be quite easy to determine. But it is correct about _t in _oldSegment never being used.
    The whole construct of segments, transitions, copies etc. is highly convoluted with dependencies all over, I still don't have it fully untangled in my head and chances that a single line change breaks things elsewhere are quite high...

  28. softhack007 commented on Jun 17, 2026

    @softhack007
    Member

    @DedeHai thanks, yes the transition/copy logic is really tangled and fragile, please see if you can make sense of it.
    I think that at least the missing stopTransition(); is correct, otherwise heap memory for _oldSegment->pixels[] might leak.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backburnerbugdiscussion

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions