In our embedded application, we have to replace ::operator new
and ::operator delete
to call a special malloc()
, to ensure that the memory is allocated correctly. The code, written with this guide this guide in mind, looks like this:
In our embedded application, we have to replace ::operator new
and ::operator delete
to call a special malloc()
, to ensure that the memory is allocated correctly. The code, written with this guide in mind, looks like this:
In our embedded application, we have to replace ::operator new
and ::operator delete
to call a special malloc()
, to ensure that the memory is allocated correctly. The code, written with this guide in mind, looks like this:
Custom operator new and operator delete
In our embedded application, we have to replace ::operator new
and ::operator delete
to call a special malloc()
, to ensure that the memory is allocated correctly. The code, written with this guide in mind, looks like this:
#include <new>
#include <stdexcept>
// Regular scalar new
void* operator new(std::size_t n) throw(std::bad_alloc)
{
using namespace std;
for (;;) {
void* allocated_memory = ::operator new(n, nothrow);
if (allocated_memory != 0) return allocated_memory;
// Store the global new handler
new_handler global_handler = set_new_handler(0);
set_new_handler(global_handler);
if (global_handler) {
global_handler();
} else {
throw bad_alloc();
}
}
}
// Nothrow scalar new
void* operator new(size_t n, std::nothrow_t const&) throw()
{
if (n == 0) n = 1;
return malloc(n);
}
// Regular array new
void* operator new[](size_t n) throw(std::bad_alloc)
{
return ::operator new(n);
}
// Nothrow array new
void* operator new[](size_t n, std::nothrow_t const&) throw()
{
return ::operator new(n, std::nothrow);
}
// Regular scalar delete
void operator delete(void* p) throw()
{
free(p);
}
// Nothrow scalar delete
void operator delete(void* p, std::nothrow_t const&) throw()
{
::operator delete(p);
}
// Regular array delete
void operator delete[](void* p) throw()
{
::operator delete(p);
}
// Nothrow array delete
void operator delete[](void* p, std::nothrow_t const&) throw()
{
::operator delete(p);
}
// Driver function to make the sample code executable.
int main()
{
int* x = new int;
delete x;
int* y = new int[10];
delete[] y;
}
Is this code correct?
In particular:
- Do I need any special alignment handling?
- Should there be any other differences between
operator new
andoperator new[]
?