Compiler GNU g++ version 3.4.4 (cygming special)
Custom allocator for vector (see below) checks a return value of
'operator new'.
If that value is NULL, the allocator "allocates" no memory.
Nevertheless the allocator produces "Segmentation fault (core dumped)".
Is it possible to correct that allocator in order to avoid such
behavior
------ foo.cpp ------
#include <vector>
#include <cstddef>
#include <iostream>
using namespace std;
template <class T> class my_alloc
{
public:
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
pointer allocate(size_type sz, void* vp = 0)
{
pointer p = static_cast<pointer>(operator new (sz *
sizeof(value_type), nothrow));
if (p == 0)
{
cerr << "[1] Unable to alloc: size = " << sz << endl;
p = static_cast<pointer>(operator new (0 * sizeof(value_type),
nothrow));
if (p == 0)
{
cerr << "[2] Unable to alloc: size = 0" << endl;
}
else
{
cerr << "[3] Alloc: size = 0" << endl;
}
}
return p;
}
void deallocate(pointer p, size_type)
{
if (p == 0)
{
cerr << "[4] Unable to dealloc" << endl;
return;
}
cerr << "[5] Dealloc" << endl;
operator delete(p, nothrow);
}
};
int main()
{
vector<int, my_alloc<int> > v (0xfffffffe);
return 0;
}
---------------------
------ Run ---
[1] Unable to alloc: size = 4294967294
[3] Alloc: size = 0
Segmentation fault (core dumped)
--------------
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn