Skip to content

d/p_realloc_malloc() can free an invalid pointer and cause crash (esp32 variants only) #6023

Done

Description

@softhack007

WLED/wled00/util.cpp

Lines 893 to 900 in 0e1f77a

// realloc with malloc fallback, original buffer is freed if realloc fails but not copied!
void *d_realloc_malloc(void *ptr, size_t size) {
void *buffer = heap_caps_realloc(ptr, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
buffer = validateFreeHeap(buffer);
if (buffer) return buffer; // realloc successful
d_free(ptr); // free old buffer if realloc failed (or min heap was exceeded)
return d_malloc(size); // fallback to malloc
}

If reallocation is successful but the remaining heap is too low, validateFreeHeap() returns nullptr. d_free(ptr) then tries to free the original pointer, which is already invalid after successful realloc().

The same problem exists in p_realloc_malloc().

The solution is to keep a copy of the pointer returned by heap_caps_realloc(), and then use it to decide if we need to free ptr: if (!newBuffer) d_free(ptr);.

Activity

  1. softhack007 commented on Dec 2, 2026

    @softhack007
    MemberAuthor

    @coderabbitai please check if my suggested fix is correct.

  2. added this to the 16.1 milestone on Dec 2, 2026
  3. self-assigned this
    on Dec 2, 2026
  4. coderabbitai commented on Dec 2, 2026

    @coderabbitai
    Contributor
    Analysis chain

    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Issue ---'
    gh api repos/wled/WLED/issues/6023 --jq '{title,body,state,html_url,user:.user.login}'
    printf '%s\n' '--- Issue comments ---'
    gh api --paginate repos/wled/WLED/issues/6023/comments --jq '.[] | {user:.user.login,body,html_url,created_at}'
    printf '%s\n' '--- Repository guidance files ---'
    for f in AGENTS.md CONTRIBUTING.md; do
      if [ -f "$f" ]; then
        echo "--- $f ---"
        cat -n "$f" | sed -n '1,200p'
      fi
    done

    Length of output: 26497


    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Relevant repository instructions ---'
    for f in AGENTS.local.md docs/cpp.instructions.md docs/hardening.instructions.md docs/securecode.instructions.md; do
      if [ -f "$f" ]; then
        printf '\n--- %s ---\n' "$f"
        cat -n "$f" | sed -n '1,180p'
      fi
    done
    printf '\n%s\n' '--- util.cpp outline ---'
    ast-grep outline wled00/util.cpp --items all --match 'realloc|malloc|validateFreeHeap|free' --view expanded
    printf '\n%s\n' '--- allocator definitions and usages ---'
    rg -n -C 4 '\b(validateFreeHeap|d_realloc_malloc|p_realloc_malloc|d_free|p_free|heap_caps_realloc)\s*\(' wled00
    printf '\n%s\n' '--- platform declarations ---'
    rg -n -C 2 'platform\s*=|platform_packages|framework\s*=|arduino-esp32|esp32.*version' platformio.ini
    printf '\n%s\n' '--- pinned revision availability ---'
    git cat-file -e 0e1f77a899d7fb02166418708e065ea94afb8c4e:wled00/util.cpp && git show 0e1f77a899d7fb02166418708e065ea94afb8c4e:wled00/util.cpp | nl -ba | sed -n '730,990p' || echo 'Pinned revision unavailable in local clone.'

    Length of output: 74638


    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Complete realloc wrapper usage search ---'
    rg -n -C 4 '\b(d_realloc_malloc|p_realloc_malloc)\b' .
    printf '\n%s\n' '--- ESP-IDF versioned allocator source and headers ---'
    for version in v5.5.4 v4.4.8; do
      for file in components/heap/heap_caps.c components/heap/include/esp_heap_caps.h; do
        echo "--- $version $file ---"
        url="https://raw.githubusercontent.com/espressif/esp-idf/$version/$file"
        curl --fail --silent --show-error --location "$url" | rg -n -C 8 'heap_caps_realloc(_base)?\s*\(|size\s*==\s*0|size is 0|size is zero|size.*zero|size.*0.*free' || true
      done
    done

    Length of output: 21215


    Script executed:

    #!/bin/bash
    set -o pipefail
    printf '%s\n' '--- ESP-IDF 5.5.4 heap_caps_realloc_base ---'
    curl --fail --silent --show-error --location https://raw.githubusercontent.com/espressif/esp-idf/v5.5.4/components/heap/heap_caps_base.c | rg -n -A 35 -B 8 'heap_caps_realloc_base\s*\('

    Length of output: 2218


    @softhack007 Your proposed check fixes the low-heap double-free in d_realloc_malloc() for nonzero sizes. It needs one more case for size == 0.

    • If heap_caps_realloc() succeeds, it consumes the original allocation. If validateFreeHeap() then rejects the result, it frees the returned allocation. The wrapper must not free ptr again.
    • If heap_caps_realloc() fails for a nonzero size, the original allocation remains valid. The wrapper can free it before the fallback.
    • For size == 0, ESP-IDF frees ptr and returns null. The proposed null check alone would therefore free ptr twice. This behavior is present in ESP-IDF 5.5.4 and 4.4.8.

    For the ESP32 implementation, this handles those cases:

    void *d_realloc_malloc(void *ptr, size_t size) {
      if (size == 0) {
        d_free(ptr);
        return nullptr;
      }
    
      void *buffer = heap_caps_realloc(ptr, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
      bool reallocated = buffer != nullptr;
      buffer = validateFreeHeap(buffer);
      if (buffer) return buffer;
      if (!reallocated) d_free(ptr);
      return d_malloc(size);
    }

    The boolean records success before validation can free buffer.

    p_realloc_malloc() does not have the same validation issue: it does not call validateFreeHeap(). It does have the zero-size double-free, so it also needs a zero-size guard before heap_caps_realloc().

    I checked the code and ESP-IDF source; I did not run hardware tests. I recommend testing successful in-place and moved reallocations, heap-validation rejection, allocation failure, and zero size.


    Learnings used

    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:16:08.536Z
    Learning: Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Comments
    
    Comments should have a space between the delimiting characters (e.g. `//`) and the comment text.
    We're gradually adopting this style - don't worry if you see older code without spaces!
    
    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:24:49.630Z
    Learning: Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Blocks
    
    Whether the opening bracket of e.g. an `if` block is in the same line as the condition or in a separate line is up to your discretion. If there is only one statement, leaving out block brackets is acceptable.
    
    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:16:08.536Z
    Learning: Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Blocks
    
    There should always be a space between a keyword and its condition and between the condition and brace.  
    Within the condition, no space should be between the parenthesis and variables.  
    Spaces between variables and operators are up to the authors discretion.
    There should be no space between function names and their argument parenthesis.
    
    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:16:08.536Z
    Learning: Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Blocks
    
    Prefer compact function parameter lists and `if` conditions rather than putting each parameter or condition part on its own line. Wrap parameter lists only when they become very long.
    
    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:16:08.536Z
    Learning: Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    Don't stress too much about style! When in doubt, just match the style in the files you're editing. 😊
    
    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:16:08.536Z
    Learning: Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Comments
    
    There is no hard character limit for a comment within a line,
    though as a rule of thumb consider wrapping after 120 characters.
    Inline comments are OK if they describe that line only and are not exceedingly wide.
    
    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:42:25.881Z
    Learning: Applies to wled00/data/pixelforge/omggif.js : Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Indentation
    
    We use tabs for indentation in Web files (.html/.css/.js) and spaces (2 per indentation level) for all other files.  
    You are all set if you have enabled `Editor: Detect Indentation` in VS Code.
    
    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:42:25.881Z
    Learning: Applies to wled00/data/index.css : Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Indentation
    
    We use tabs for indentation in Web files (.html/.css/.js) and spaces (2 per indentation level) for all other files.  
    You are all set if you have enabled `Editor: Detect Indentation` in VS Code.
    

    You are interacting with an AI system.

  5. added a commit that references this issue on Dec 3, 2026
    c38d832
  6. softhack007 commented on Dec 3, 2026

    @softhack007
    MemberAuthor

    @coderabbitai do we need special handling for ptr == nullptr or is the suggested fix sufficient? Check against the behaviour of a plain heap_caps_realloc(...) call.

  7. coderabbitai commented on Dec 3, 2026

    @coderabbitai
    Contributor
    Analysis chain

    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Issue and suggested fix ---'
    gh api repos/wled/WLED/issues/6023 --jq '{title,body}'
    gh api --paginate repos/wled/WLED/issues/6023/comments --jq '.[] | {user:.user.login,body}'
    printf '\n%s\n' '--- allocator function outline ---'
    ast-grep outline wled00/util.cpp --items all --match 'realloc|malloc|validateFreeHeap|free' --view expanded
    printf '\n%s\n' '--- allocator code ---'
    rg -n -C 7 '\b(validateFreeHeap|d_realloc_malloc|p_realloc_malloc|d_malloc|p_malloc|d_free|p_free)\s*\(' wled00/util.cpp
    printf '\n%s\n' '--- platform settings ---'
    rg -n -C 2 'platform\s*=|platform_packages|framework\s*=' platformio.ini
    printf '\n%s\n' '--- ESP-IDF v5.5.4 implementation ---'
    curl --fail --silent --show-error --location https://raw.githubusercontent.com/espressif/esp-idf/v5.5.4/components/heap/heap_caps_base.c | rg -n -A 70 -B 8 'heap_caps_realloc_base\s*\(|heap_caps_malloc_base\s*\(|heap_caps_free\s*\('
    printf '\n%s\n' '--- ESP-IDF v4.4.8 implementation ---'
    curl --fail --silent --show-error --location https://raw.githubusercontent.com/espressif/esp-idf/v4.4.8/components/heap/heap_caps.c | rg -n -A 60 -B 8 'heap_caps_realloc\s*\(|heap_caps_malloc\s*\(|heap_caps_free\s*\('
    printf '\n%s\n' '--- ESP-IDF API docs ---'
    for version in v5.5.4 v4.4.8; do
      echo "--- $version ---"
      curl --fail --silent --show-error --location "https://raw.githubusercontent.com/espressif/esp-idf/$version/components/heap/include/esp_heap_caps.h" | rg -n -A 27 -B 15 'heap_caps_realloc\s*\('
    done

    Length of output: 59593


    Script executed:

    #!/bin/bash
    printf '%s\n' '--- WLED free helper definitions ---'
    rg -n -C 6 '\b(?:d_free|p_free)\s*\(' wled00 -g '*.h' -g '*.cpp' | head -n 160
    printf '\n%s\n' '--- ESP-IDF 4.4.8 malloc base ---'
    curl --fail --silent --show-error --location https://raw.githubusercontent.com/espressif/esp-idf/v4.4.8/components/heap/heap_caps.c | rg -n -A 35 -B 8 'heap_caps_malloc_base\s*\(' | head -n 75
    printf '\n%s\n' '--- ESP-IDF 5.5.4 realloc failure hook ---'
    curl --fail --silent --show-error --location https://raw.githubusercontent.com/espressif/esp-idf/v5.5.4/components/heap/heap_caps.c | rg -n -A 16 -B 5 'heap_caps_realloc\s*\('

    Length of output: 14330


    @softhack007 No additional ptr == nullptr branch is needed for memory safety in the fix from my previous reply.

    • If ptr == nullptr and size > 0, plain heap_caps_realloc() attempts a new allocation. The proposed wrapper does the same.
    • If that allocation fails, the wrapper calls d_free(nullptr), which is safe, then tries d_malloc(size). If validation rejects a successful allocation, it frees that allocation before the fallback.
    • If ptr == nullptr and size == 0, the guard calls d_free(nullptr) and returns nullptr. The checked ESP-IDF implementations also return nullptr for a plain call with these arguments.

    The wrapper is not identical to a plain heap_caps_realloc() call. It can reject an allocation through validateFreeHeap() and try a fallback. For a non-null pointer and nonzero size, it also frees the original buffer on allocation failure; a plain call leaves that buffer allocated. An explicit null-pointer branch would only be needed if you want the initial allocation to use d_malloc() directly.

    I checked the ESP-IDF 5.5.4 and 4.4.8 implementations. I did not run hardware tests.


    Learnings used

    Learnt from: CR
    Repo: wled/WLED PR: 0
    File: CONTRIBUTING.md:0-0
    Timestamp: 2026-10-31T16:16:08.536Z
    Learning: Applicability reference:
    AGENTS.md: # AGENTS.md — WLED AI Coding Agent & AI Code Review Reference
    ## Required User Agreement
    ### No agent-posted replies or issues
    Reviewer time is limited, and checking long AI-generated explanations for reasoning errors and hallucinations is costly. Even after the user agreement is confirmed:
    
    - Creating or updating pull requests remains allowed (after the user agreement is confirmed). Keep PR descriptions concise and factual, and include a summary written by the user in their own words, leading with what they want to achieve or what bothers them in plain language, as described in [CONTRIBUTING.md](CONTRIBUTING.md#opening-issues--feature-requests).
    
    Source excerpt:
    # Thank you for making WLED better!
    
    ## Coding Guidelines
    
    ### Code style
    
    #### Comments
    
    Comments should have a space between the delimiting characters (e.g. `//`) and the comment text.
    We're gradually adopting this style - don't worry if you see older code without spaces!
    
    Learnt from: DedeHai
    Repo: wled/WLED PR: 4791
    File: wled00/util.cpp:737-743
    Timestamp: 2025-09-15T19:13:56.469Z
    Learning: In WLED's util.cpp, the *_realloc_malloc functions (p_realloc_malloc and d_realloc_malloc) are intentionally designed to free the original buffer on realloc failure and allocate a new buffer, implementing a "replace buffer" semantic rather than traditional realloc behavior. This is documented in the function comments and is the intended design by the author DedeHai.
    
    Learnt from: softhack007
    Repo: wled/WLED PR: 0
    File: :0-0
    Timestamp: 2026-10-03T14:59:43.661Z
    Learning: In wled/WLED, softhack007 prefers contributors to answer maintainer questions directly with short explanations in their own words, even if the explanations are technically imprecise or the English is imperfect. Contributors should state uncertainty and actual test results rather than relay unverified AI-generated technical answers. AI may assist with translation or wording, but should not manufacture explanations that shift fact-checking and AI-session supervision onto maintainers.
    

    You are interacting with an AI system.

  8. coderabbitai commented on Dec 3, 2026

    @coderabbitai
  9. removed this from the 16.1 milestone on Dec 3, 2026
  10. added a commit that references this issue on Dec 3, 2026
    ea4ca10
  11. added a commit that references this issue on Dec 3, 2026
    bee516b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions