"Andrew Pinski" <[EMAIL PROTECTED]> writes:

| On 9/7/07, Chris Lattner <[EMAIL PROTECTED]> wrote:
| 
| > 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 was looking for something else in the standard and found this (5.3.4/7):
| [Note: If the library allocation function is called, the pointer
| returned is distinct from the pointer to any other object. ]
| 
| Which means it has to act like malloc.

As has been pointed out, that is not exactly true -- although I
suspect the intent is to have the default operator new behaves like
malloc.

The difference is that, being distinct from a pointer to any other
object is not the same as not aliasing any other pointer.

Furthermore, the issue is more subtle/non-trivial for C++ because
users can provide their own allocators.


Consider the following:

   struct ChunkAlloc {
     ChunkAlloc();

     void* allocate(size_t n);
     void* deallocate(void*) { } 

   private:
     enum { size = 4096 };
     char chunk[size];          // assume this is suitable aligned
     char* next
   };

   ChunkAlloc::ChunkAlloc() 
      : next(chunk) { }

   void*
   ChunkAlloc::allocate(size_t n)
   {
     if (n == 0) return malloc(1);
     if ((chunk + size - next) >= n) {
        char* mem = next;
        next += n;
        return mem;
     }
     throw bad_alloc;        
   }


Do you believe that allocator is prohibited by the C++ standard?

Notice that the first pointer returned for non-zero memory chunk
request has the same address (as void*) as the allocator object --
under usual GCC ABI.

-- Gaby

Reply via email to