[libc-commits] [libc] [libc][CPP] make the string trap on OOM (PR #172260)

Schrodinger ZHU Yifan via libc-commits libc-commits at lists.llvm.org
Mon Dec 15 00:01:17 PST 2025


https://github.com/SchrodingerZhu created https://github.com/llvm/llvm-project/pull/172260

This PR makes the string trap on OOM.

Previously, the `__builtin_unreachable` has made debugging tricky as it makes the control flow of OOM as an undefined behavior.
We can run into OOM with testing configuration easily where memory is statically bounded.

We did not settle with the best solution of this but making it trap is at least better than UB 
in this case.


>From d6a908dd39c28756f8d1242ada4b1f391ecf0cfd Mon Sep 17 00:00:00 2001
From: Schrodinger ZHU Yifan <i at zhuyi.fan>
Date: Mon, 15 Dec 2025 02:57:28 -0500
Subject: [PATCH] [libc][CPP] make the string trap on OOM

---
 libc/src/__support/CPP/string.h | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/libc/src/__support/CPP/string.h b/libc/src/__support/CPP/string.h
index 1ac04c7f1f9dc..a4de1ace02d22 100644
--- a/libc/src/__support/CPP/string.h
+++ b/libc/src/__support/CPP/string.h
@@ -136,9 +136,10 @@ class string {
                               new_capacity)) {
       buffer_ = static_cast<char *>(Ptr);
       capacity_ = new_capacity;
-    } else {
-      __builtin_unreachable(); // out of memory
     }
+    // Out of memory: this is not handled in current implementation,
+    // We trap the program and exits.
+    __builtin_trap();
   }
 
   LIBC_INLINE void resize(size_t size) {



More information about the libc-commits mailing list