4

I am new to C++ and I have something unclear:

#include <iostream>
using namespace std;

double* foo(void)
{
    double* b = new double[100];
    return b;
}

int main()
{
    double* a = foo();

    delete [] a;
    return 0;
}

Is there something wrong with this code? I mean whether the way I use operator delete is right? I assign the pointer b which points to the allocated memory in foo function to pointer a outside foo, can I release memory by means of delete[]a in main? I don't have any idea how does the compiler calculate the number of bytes to release when execute delete[]. Thanks

Scooter
  • 6,802
  • 8
  • 41
  • 64
feirainy
  • 497
  • 1
  • 4
  • 11
  • 1
    possible duplicate of [How does delete\[\] "know" the size of the operand array?](http://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array) – Mat Sep 23 '11 at 14:50

2 Answers2

5

The code is correct (though not usually part of any well-written modern C++ program).

Dynamically allocated arrays are stored with hidden information about their size so that delete[] p knows how many elements to delete.


If you're curious about the details, you can rig up a little test class and take advantage of the member allocation operators:

struct ArrayMe
{
  static void * operator new[](size_t n) throw(std::bad_alloc)
  {
    void * p = ::operator new[](n);
    std::cout << "new[]ed " << n << " bytes at " << p << "." << std::endl;
    return p;
  }

  static void operator delete[](void * p, std::size_t n) throw()
  {
    std::cout << "delete[]ing " << n << " bytes at " << p << "." << std::endl;
    ::operator delete[](p);
  }

  double q;
};

Now say:

std::cout << "sizeof(ArrayMe) = " << sizeof(ArrayMe) << std::endl;
ArrayMe * const a = new ArrayMe[10];
delete[] a;
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • “Arrays are stored with hidden information about their size” : this stands for dynamically allocated arrays. – Benoit Sep 23 '11 at 14:56
  • 1
    Wait! Did you just provide code to a C++ newbie that uses an exception specification!?! Shame on you. – deft_code Sep 23 '11 at 15:17
  • 2
    @deft_code: I believe those are mandatory for the allocation operators. Or maybe that's only for the global ones, I'm not sure. – Kerrek SB Sep 23 '11 at 15:39
1

Call delete [] to delete C-style arrays allocated with operator new []. Delete [] will know how many bytes were allocated by operator new[].

Call delete to delete objects allocated with operator new (no brackets). Never, ever mix them! I.e. never call delete [] on something allocated with operator new, and never call delete on something allocated with operator new [].

James Johnston
  • 9,264
  • 9
  • 48
  • 76