This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [RFC] Marking C++ new operator as malloc?


Hi,

On Fri, Sep 07, 2007 at 06:30:33PM -0700, Chris Lattner wrote:
> On Sep 7, 2007, at 1:53 PM, Martin Jambor wrote:
>> when trying  to analyse dynamically  allocated objects in C++,  I came
>> across the need to identify results  of the new operator (at least the
>> non-overridden  standard  one)   as  malloc-allocated.   The  cleanest
>> approach would probably be to  mark the new operator function with the
>> malloc attribute.   So I did  that (see the extra-short  patch below),
>> bootstrapped c  and c++ on  i686-linux (with "all,fold"  checking) and
>> ran the test suite. To my surprise, there were no new regressions.
>>
>> I  am  now  wondering  why  the  function  is  not  marked  as  malloc
>> already. In fact, its implementation  always returns what it gets from
>> the built-in malloc. Are there  any known issues or concerns with this
>> that the test suite cannot reveal? Can anyone comment on this?
>
> It is unclear whether this is safe.  Nothing in the standard AFAIK requires 
> the operator new be implemented in terms of malloc, and users are allowed 
> to override it.

I have just  explained in another email that  user-overridden new's do
not  seem to  be  a problem  as the  attribute  is given  only to  the
libstdc++ one.

The reason  why I believe the patch  is safe not only  in practice but
also  in principle is  that the  libstc++ operator  new implementation
(see  below) returns  what  it  gets from  malloc  which is  hopefully
mallocish enough  (and the  operator does not  do any  dangerous stuff
with the pointer either).


Martin


--- cut here ---
_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) throw (std::bad_alloc)
{
  void *p;

  /* malloc (0) is unpredictable; avoid it.  */
  if (sz == 0)
    sz = 1;
  p = (void *) malloc (sz);
  while (p == 0)
    {
      new_handler handler = __new_handler;
      if (! handler)
#ifdef __EXCEPTIONS
        throw bad_alloc();
#else
        std::abort();
#endif
      handler ();
      p = (void *) malloc (sz);
    }

  return p;
}
--- cuthere ---


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]