You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
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.
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.
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.
@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.
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 ChoicesDesign Choice 1: Should `purgeSegments()` be called unconditionally or only when deletions occurred?
Options Considered:
Call purgeSegments() unconditionally after processing the segment array
Call purgeSegments() only when at least one segment was deleted (check deleted > 0)
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!
@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.
#!/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 forwardecho"=== 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
#!/bin/bash# Check current destructor in mainecho"=== 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.hecho"=== 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/bashecho"=== 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 directlyecho"=== 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.
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.
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.
#!/bin/bashecho"=== 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/bashecho"=== 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:
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 areaif (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 copydelete _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
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?
#!/bin/bashecho"=== 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 copydelete _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.
#!/bin/bashecho"=== 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 — _oldSegmentalways 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 nullif (!stop) return;
if (orig.pixels) {
pixels = static_cast<uint32_t*>( // ← allocate NEW bufferallocate_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.
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
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.
#!/bin/bashecho"=== 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():
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.
@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...
@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.
Activity
softhack007 commentedon Nov 22, 2024
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
DedeHai commentedon Nov 23, 2024
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 bydeserializeSegmentcalling the segmentsetUp()function. So the root cause may be even coming from the UI or incorrect handling of the UI decoding.netmindz commentedon Nov 25, 2024
Sounds like not a blocker for rc1 then
blazoncek commentedon Nov 26, 2024
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.
DedeHai commentedon Jul 24, 2025
FYI: this is fixed in 0.16
softhack007 commentedon Mar 9, 2026
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
WLED/wled00/json.cpp
Lines 499 to 501 in 53d6c4b
softhack007 commentedon Mar 9, 2026
@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
mainbranch. 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.softhack007 commentedon Mar 9, 2026
oopsie - mixed things up - this issue is about deleting segments, not about the preset deletion bug 😅
coderabbitai commentedon Mar 9, 2026
Coding Plan
Summary
purgeSegments()so deleted segments are always compacted out of the vectorSegmentdestructor by freeing the Transition pointerDesign Choices
Design Choice 1: Should `purgeSegments()` be called unconditionally or only when deletions occurred?
Options Considered:
purgeSegments()unconditionally after processing the segment arraypurgeSegments()only when at least one segment was deleted (checkdeleted > 0)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: CallpurgeSegments()whendeleted > 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.
wled00/json.cpp, locate thepurgeSegments()call after the segment array processing loop (around line 487)if (strip.getSegmentsNum() > 3 && deleted >= strip.getSegmentsNum()/2U)to simplyif (deleted)(orif (deleted > 0))strip.suspend()/strip.resume()wrapper, so service() safety is maintained🤖 Prompt for AI agents
Phase 2: Fix Segment Destructor Memory Leak
This phase addresses a secondary bug discovered during analysis - the
Segmentdestructor 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.wled00/FX.h, locate the~Segment()destructor (around line 618)if (_t) { delete _t; _t = nullptr; }or callstopTransition()if accessible from the destructor contextdeallocateData()andp_free(pixels)to maintain proper cleanup orderstopTransition()is a public method that doesdelete _t; _t = nullptr;, so it can be called directly if preferred for consistency🤖 Prompt for AI agents
Research
WLED stores segments in a
std::vector<Segment>within theWS2812FXclass. Segment deletion is implemented as a "soft delete" - settingstop=0marks the segment inactive but leaves it in the vector. ThepurgeSegments()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, theSegmentdestructor has a memory leak - it does not free the_t(Transition) pointer.🚀 Next Steps
🤖 All AI agent prompts combined
💡 Iterate on the plan with:
@coderabbitai <feedback>💬 Have feedback or questions? Drop into our discord!
softhack007 commentedon Mar 9, 2026
@coderabbitai please review and inspect the current source code. According to this comment the problem should be solved.
14 remaining items
softhack007 commentedon Jun 17, 2026
@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
@coderabbitai please trace through the commit history of
main, and find the commit which removed thestopTransition();call in the~segmentdestructor. Also check if there is a PR or issue ticket or other justification that can explain this removal.coderabbitai commentedon Jun 17, 2026
🧩 Analysis chain
🏁 Script executed:
Length of output: 496
🏁 Script executed:
Length of output: 701
🏁 Script executed:
Length of output: 1631
🏁 Script executed:
Length of output: 1554
🏁 Script executed:
Length of output: 510
🏁 Script executed:
Length of output: 25250
🏁 Script executed:
Length of output: 982
🏁 Script executed:
Length of output: 6132
🏁 Script executed:
Length of output: 1241
@softhack007— Found it. ThestopTransition()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 withclearName()andd_free(pixels)was added for the new pixel buffer, butstopTransition()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 (beforedeallocateData()) is the correct fix, with no risk of double-free sincestopTransition()is guarded byif (_t != nullptr).✏️ Learnings added
softhack007 commentedon Jun 17, 2026
The big "change everything" PR 👀 . I agree it was likely an accident to remove
stopTransition();softhack007 commentedon Jun 17, 2026
@coderabbitai please double-check if its safe to add
stopTransition();back to the destructor (beforedeallocateData()). Is it possible that_oldSegmentcould 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.coderabbitai commentedon Jun 17, 2026
🧩 Analysis chain
🏁 Script executed:
Length of output: 20453
🏁 Script executed:
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):new Segment(*this)on line 325 copies*this— including its already-non-null_tpointer. Because there is no longer an explicit copy constructor in the current code (the oldSegment(const Segment &orig)was removed in PR#4658), the compiler generates a default member-wise copy. After this line:If
stopTransition()is naively added to~Segment(), the destruction chain becomes: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_oldSegmentat all. It simply allocated_t = new Transition(dur)with no segment copy. The explicit copy constructorSegment(const Segment &orig)that was declared (line 499 in old code) handled_tcorrectly in that simpler world. When PR#4658introduced_oldSegmentas a full segment copy insideTransition, 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->_timmediately after creating the copy, instartTransition(). This prevents_oldSegmentfrom ever thinking it owns theTransition:The same null assignment is needed in the "already in transition" copy path (line 301).
Alternatively (equivalent safety), null it in
~Transition()before callingdelete _oldSegment:Step 2 (only after Step 1): Add
stopTransition()back to~Segment():Summary
stopTransition()to~Segment()safe?_oldSegment->_t_oldSegmenthave a_tattached?_tis set, and no copy constructor nullifies it~Transition()lead to a loop?_oldSegment->_tafter copy instartTransition()(or in~Transition()), then addstopTransition()to destructor🐇 🔍
DedeHai commentedon Jun 17, 2026
good call, I forgot about the
_tin_oldSegmentand the rabbit is spot on for once ;)softhack007 commentedon Jun 17, 2026
@coderabbitai i'm still unsure if the pointer copy in
_oldSegment->_tis 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?coderabbitai commentedon Jun 17, 2026
🧩 Analysis chain
🏁 Script executed:
Length of output: 13613
@softhack007— The answer is clear:_oldSegment->_tis never accessed anywhere and is purely a spurious artifact of the shallow memberwise copy.Evidence
The search for any code that dereferences
->_ton_oldSegmentreturned zero results. Looking at every place_oldSegmentis actually used:_oldSegmentstartTransition()palette,colors[], checksisActive()stopTransition()~Transition()delete _oldSegment(frees the copy)getOldSegment()getOldSegment()palette,colors,pixels— never_tThe
_tinside_oldSegmentis never read or written after the copy is made. It only exists becausenew Segment(*this)is a memberwise copy and_tis 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():This is safe and complete:
_oldSegment->_tis 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 addstopTransition()back to~Segment()with no risk of recursion or double-free.✏️ Learnings added
softhack007 commentedon Jun 17, 2026
WLED/wled00/FX.h
Line 625 in 8dfd2cf
@coderabbitai is _oldSegment using a copy of the
pixelsarray pointer, or will it always have its ownpixels?coderabbitai commentedon Jun 17, 2026
🧩 Analysis chain
🏁 Script executed:
Length of output: 18523
@softhack007—_oldSegmentalways has its own independently allocatedpixelsbuffer — it is a deep copy, never a shared pointer.The copy constructor in
FX_fcn.cppmakes this explicit:Every path that creates a
Segmentcopy (new Segment(*this)instartTransition()) goes through this constructor, which immediately nullspixelsand then allocates a fresh buffer. When~Transition()eventually callsdelete _oldSegment, thep_free(pixels)in~Segment()frees the copy's own allocation — completely independent from the parent segment'spixels.So to summarize the destructor safety picture:
_oldSegmentpixelsnamedata_t_oldSegment->_t = nullptrfix firstThe conclusion from the thread still holds: the two-step fix (
_oldSegment->_t = nullptrin~Transition(), thenstopTransition()in~Segment()) is the correct and complete approach, andpixelsis not an additional concern.softhack007 commentedon Jun 17, 2026
@coderabbitai your two statements about the segment copy constructor (explicit / implicit) seem contradicting. please clarify.
#4304 (comment)
#4304 (comment)
coderabbitai commentedon Jun 17, 2026
🧩 Analysis chain
🏁 Script executed:
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
mainbranchThe explicit copy constructor was not removed — it exists in
FX_fcn.cppand already handles_tcorrectly:_tis set tonullptrright after thememcpy. This means_oldSegment->_tis alwaysnullptrafternew Segment(*this)instartTransition(). 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
#4658"_oldSegment->_t"_t_oldSegment->_t = nullptrin~Transition()first"The actual fix required
Just one change — add
stopTransition()back to~Segment()beforedeallocateData():No changes to
~Transition()orstartTransition()are needed. The copy constructor already makes_oldSegment->_t == nullptrinvariant, so there is no recursion or double-free risk.🐇 straightens ears sheepishly
✏️ Learnings added
DedeHai commentedon Jun 17, 2026
@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
_tin_oldSegmentnever 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...
softhack007 commentedon Jun 17, 2026
@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.