Malloc crashes instead of returning NULL when it can't allocate memory

This code works:

#include <stdint.h>
#include <stdlib.h>
#include <core/log.h>

#define MEMORY_TO_ALLOCATE 30000

int32_t test_app(void *p) {

  (void)(p);

  /* Allocate memory */
  void *ptr = malloc(MEMORY_TO_ALLOCATE);

  FURI_LOG_I("test_app", "Allocated %d bytes at address 0x%lx", MEMORY_TO_ALLOCATE, (uint32_t)ptr);

  /* Free the memory if it was allocated */
  if(ptr)
    free(ptr);

  FURI_LOG_I("test_app", "Freed %d bytes at address 0x%lx", MEMORY_TO_ALLOCATE, (uint32_t)ptr);

  return 0;
}

However, change MEMORY_TO_ALLOCATE to 300000 - which of course is bound to fail since it exceeds the memory available and this happens:

image

I expected malloc to return NULL but instead it crashes the system.

I found this interesting excerpt in this recent interview:

We have designed malloc in such a way that it either returns something valid or causes the system to crash.

So that’s consistent with that I’m seeing. However, a few lines later, I read this:

A note from the PVS-Studio developers: For our users, we would like to point out that the issue regarding the special malloc function is no longer relevant. There is a special markup, it tells the analyzer to consider that the function always returns a non-null pointer:

This is a bit confusing, as I’m both reading that whatever was wrong with malloc is now fixed, yet it still won’t return a NULL pointer if it can’t allocate the memory. This is non-standard and unhelpful, as there is no way for an app to abort gracefully in case there isn’t enough memory.

EDIT: I guess I read that sentence wrong: they meant to say malloc works in a non-standard way but PVS Studio doesn’t throw a fit over it anymore

Is there another mechanism to test whether malloc will succeed before calling it to avoid risking crashing the Flipper?