On 12/17/2016 10:58 AM, Janus Weil wrote: > 2016-12-16 19:46 GMT+01:00 Pedro Alves <pal...@redhat.com>: > So, it seems like it would be a good idea to follow your suggestion > from PR 78822: > > >> You can replace the global operator new/new[] to call xmalloc instead of >> malloc. >> Then memory allocation by std::string etc. ends up in xmalloc -> >> xmalloc_failed. >> That's what I did for GDB: >> >> https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=blob;f=gdb/common/new-op.c;h=c67239cbe87c1f7e22e234a1a2cc2920f9ed22a4;hb=HEAD > > I'm certainly not the right person to implement this in GCC, though > (and I'll probably discard my idea of using std::string for PR 78822 > and follow the alternative implementation from comment 14). > > But I think that, given the amount of STL containers already used in > GCC, it should definitely be clarified whether this is necessary ...
TBC, STL containers are a red herring here, and a bit orthogonal. The root issue is that any "new" expression that calls the global (non-placement-new, non-class-specific) operator new/new[] in GCC is "unprotected" and inconsistent with xmalloc already, because the default operator new/new[] calls malloc. I.e., "new" expressions are already "unprotected" in exactly the same way as allocations inside STL containers. Some classes have class-specific 'operator new' implementations (grep for "operator new"), but seems to me many don't. E.g., grep for " = new": ... auto-profile.c: autofdo_source_profile *map = new autofdo_source_profile (); auto-profile.c: function_instance *s = new function_instance (name, head_count); auto-profile.c: afdo_string_table = new string_table (); spellcheck.c: edit_distance_t *v0 = new edit_distance_t[len_s + 1]; ... new[] calls I think are more likely to cause trouble due to run-time variable size, though non-array new calls can certainly fail too. You should be able to trigger/see the issue by just hacking some: char *p = new char [-1]; somewhere in the compiler. The compiler will likely crash with something like: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) ... instead of the xmalloc_failed message. and then compare with a "xmalloc (-1)" call. TBC, replacing global operator new is perfectly defined/valid C++. The overloads in question are specified as "replaceable". See: http://en.cppreference.com/w/cpp/memory/new/operator_new Thanks, Pedro Alves