Correct way to prevent memory allocation fails

I am regularly seeing MBUF_REALLOC failing on my platform.
Although the comments suggest it should recover from this, most of the time there is subsequently an attempt at resizing an mbuf with a null pointer.

void mbuf_resize(struct mbuf *a, size_t new_size) {
if (new_size > 0) printf(“mbuf resize %p, %d → %d\n”, a->buf, a->size, new_size);
if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
char *buf = (char ) MBUF_REALLOC(a->buf, new_size);
/

* In case realloc fails, there’s not much we can do, except keep things as
* they are. Note that NULL is a valid return value from realloc when
* size == 0, but that is covered too.
*/
if (buf == NULL && new_size != 0) {
return;
}
a->buf = buf;
a->size = new_size;
}

However, this case is not handled in the calling function, mg_do_recv():

if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) {
mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len);
}
buf = nc->recv_mbuf.buf + nc->recv_mbuf.len;

buf will be blown off the end of nc->recv_mbuf.buf, resulting in an invalid or null pointer.

What’s the correct way to ensure that the server operates within its memory limits?

Mongoose 6.18, LwIP, FreeRTOS, NXP K66