diff --git a/src/platform/nrf54l15/Arduino.h b/src/platform/nrf54l15/Arduino.h index c67628afa..0d7449e89 100644 --- a/src/platform/nrf54l15/Arduino.h +++ b/src/platform/nrf54l15/Arduino.h @@ -599,8 +599,12 @@ class String void assign(const char *s, unsigned int n) { - if (n >= _cap) - reserve(n + 1); + // reserve() keeps the old (smaller) buffer on OOM, so a failed grow must abort the + // write: memcpy'ing n >= _cap bytes would overflow into adjacent heap. + if (n + 1 == 0) + return; // n + 1 would wrap + if (n >= _cap && !reserve(n + 1)) + return; if (_buf) { memcpy(_buf, s, n); _buf[n] = 0; @@ -612,21 +616,27 @@ class String if (!s || n == 0) return; unsigned newlen = _len + n; - if (newlen >= _cap) - reserve(newlen + 1); + if (newlen < _len || newlen + 1 == 0) + return; // length arithmetic wrapped + if (newlen >= _cap && !reserve(newlen + 1)) + return; // OOM: keep the existing content intact instead of writing past the buffer if (_buf) { memcpy(_buf + _len, s, n); _len = newlen; _buf[_len] = 0; } } - void reserve(unsigned int n) + bool reserve(unsigned int n) { + if (n == 0) + return false; char *b = (char *)realloc(_buf, n); if (b) { _buf = b; _cap = n; + return true; } + return false; } };