[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 14:02:06 PST 2025
https://github.com/SchrodingerZhu updated https://github.com/llvm/llvm-project/pull/172260
>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 1/3] [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) {
>From ed269c107b8accd1e338110a78dfcba0b64ae174 Mon Sep 17 00:00:00 2001
From: Schrodinger ZHU Yifan <i at zhuyi.fan>
Date: Mon, 15 Dec 2025 03:10:36 -0500
Subject: [PATCH 2/3] early return on successful path
---
libc/src/__support/CPP/string.h | 2 ++
1 file changed, 2 insertions(+)
diff --git a/libc/src/__support/CPP/string.h b/libc/src/__support/CPP/string.h
index a4de1ace02d22..d4cf3b89bff23 100644
--- a/libc/src/__support/CPP/string.h
+++ b/libc/src/__support/CPP/string.h
@@ -132,10 +132,12 @@ class string {
// by 8 is cheap. We guard the extension so the operation doesn't overflow.
if (new_capacity < SIZE_MAX / 11)
new_capacity = new_capacity * 11 / 8;
+
if (void *Ptr = ::realloc(buffer_ == get_empty_string() ? nullptr : buffer_,
new_capacity)) {
buffer_ = static_cast<char *>(Ptr);
capacity_ = new_capacity;
+ return;
}
// Out of memory: this is not handled in current implementation,
// We trap the program and exits.
>From db3092862fe6b9a8dbad7bc05ccd68a02cc6c1e5 Mon Sep 17 00:00:00 2001
From: Schrodinger ZHU Yifan <i at zhuyi.fan>
Date: Mon, 15 Dec 2025 17:01:29 -0500
Subject: [PATCH 3/3] fix formatting
---
libc/src/__support/CPP/string.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/libc/src/__support/CPP/string.h b/libc/src/__support/CPP/string.h
index d4cf3b89bff23..04f0e9538d03e 100644
--- a/libc/src/__support/CPP/string.h
+++ b/libc/src/__support/CPP/string.h
@@ -132,7 +132,7 @@ class string {
// by 8 is cheap. We guard the extension so the operation doesn't overflow.
if (new_capacity < SIZE_MAX / 11)
new_capacity = new_capacity * 11 / 8;
-
+
if (void *Ptr = ::realloc(buffer_ == get_empty_string() ? nullptr : buffer_,
new_capacity)) {
buffer_ = static_cast<char *>(Ptr);
More information about the libc-commits
mailing list