← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Stack Overflow from Deep Recursion

php PHP 5.0+ Intermediate

TL;DR

PHP has no configurable stack size limit — deep recursion causes a fatal segfault or memory exhaustion, not a catchable exception.

Explanation

PHP's call stack is limited by the OS stack size (typically 8MB on Linux). Deep recursion exhausts it and causes a segfault or memory_limit error — neither is catchable with try/catch. Practical limit is roughly 500–5000 nested calls depending on frame size. Solutions: convert tail-recursive functions to iterative loops, use a trampoline pattern, or process trees iteratively with an explicit stack (SplStack). xdebug.max_nesting_level (default 256) provides an earlier, catchable limit via E_ERROR.

Common Misconception

PHP will throw a catchable exception on stack overflow — it segfaults or hits memory_limit, both of which are uncatchable fatal errors.

Why It Matters

Recursive algorithms on user-supplied data (like parsing nested JSON or tree structures) can be exploited to crash PHP via stack exhaustion.

Common Mistakes

  • Recursive tree traversal without depth limit.
  • Not converting obvious tail recursion to iteration.
  • Setting xdebug.max_nesting_level too high — delays the crash.

Code Examples

✗ Vulnerable
function factorial(int $n): int {
    return $n <= 1 ? 1 : $n * factorial($n - 1);
}
factorial(100000); // Segfault
✓ Fixed
function factorial(int $n): int {
    $result = 1;
    for ($i = 2; $i <= $n; $i++) $result *= $i;
    return $result;
}

// Iterative tree traversal using explicit stack
function traverse(Node $root): void {
    $stack = new \SplStack();
    $stack->push($root);
    while (!$stack->isEmpty()) {
        $node = $stack->pop();
        process($node);
        foreach ($node->children as $child) $stack->push($child);
    }
}

Added 22 Mar 2026
Views 22
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping F 0 pings S 2 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 2 pings S 0 pings M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S 2 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Amazonbot 8 Unknown AI 3 Perplexity 3 ChatGPT 2 Google 2 Meta AI 1 Ahrefs 1
crawler 18 crawler_json 1 pre-tracking 1
DEV INTEL Tools & Severity
🟠 High ⚙ Fix effort: Medium
⚡ Quick Fix
Convert recursive functions to iterative using SplStack or a while loop. Set xdebug.max_nesting_level=500 to get an early catchable error in dev.
📦 Applies To
PHP 5.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
function.*\(.*\).*{[^}]*\$.*\(
Auto-detectable: ✗ No phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: High Context: Function Tests: Update
CWE-674 CWE-400

✓ schema.org compliant