Skip to content

Commit 16329fd

Browse files
committed
Override new and delete operators to trap errors
When new or new[] fails to allocate space trigger an error.
1 parent da4787f commit 16329fd

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

hal/common/retarget.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
#include "mbed_interface.h"
2424
#include "SingletonPtr.h"
2525
#include "PlatformMutex.h"
26+
#include "mbed_error.h"
27+
#include <stdlib.h>
2628
#if DEVICE_STDIO_MESSAGES
2729
#include <stdio.h>
2830
#endif
@@ -724,3 +726,34 @@ extern "C" void __env_unlock( struct _reent *_r )
724726
#endif
725727

726728
} // namespace mbed
729+
730+
void *operator new(std::size_t count)
731+
{
732+
void *buffer = malloc(count);
733+
if (NULL == buffer) {
734+
error("Operator new out of memory\r\n");
735+
}
736+
return buffer;
737+
}
738+
739+
void *operator new[](std::size_t count)
740+
{
741+
void *buffer = malloc(count);
742+
if (NULL == buffer) {
743+
error("Operator new[] out of memory\r\n");
744+
}
745+
return buffer;
746+
}
747+
748+
void operator delete(void *ptr)
749+
{
750+
if (ptr != NULL) {
751+
free(ptr);
752+
}
753+
}
754+
void operator delete[](void *ptr)
755+
{
756+
if (ptr != NULL) {
757+
free(ptr);
758+
}
759+
}

0 commit comments

Comments
 (0)