Thread: delete and delete []

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    69

    delete and delete []

    What's exactly the difference between delete and delete [] ?

    I read that delete [] is used when deleting an array,because it deletes all elements in the array and the array itself

    And if i do this ??

    Code:
    char  c = new char[20];
    
    delete c; // instead of    delete [] c
    is it an error ?? compilers never report errors in these cases,but
    is the array really being deleted?


    I tried also to create an array of pointers to objects and verify that delete []
    calls actually the destructors of all objects in the array before
    deleting the array itself

    In order to do that i put a printf in the class' destructor,but it wasn't displayed

    Code:
    SomeClass  **objectptr = new SomeClass*[20];
    
     // create the objects
    
    for(int i = 0;i < 20;i++)
     objectptr[i] = new SomeClass();
    
    //..
    
    delete [] objectptr;  // this doesn't delete the objects...but just
                                    // the memory occupied by their pointers
    How do you use delete [] ?
    Last edited by Lionel; 05-18-2005 at 04:06 PM.

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    You use new and delete to allocate and deallocate a single object. You use new[] and delete[] to allocate and deallocate a group of objects in contigious memory.

    so:
    Code:
    int *ptr1 = new int;
    int *ptr2 = new int[10];
    delete ptr1;
    delete[] ptr2;

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    127
    Code:
    char  c = new char[20];
    delete c; // instead of    delete [] c
    i don't think it is an error, but it will bring some bugs to you, e.g. leak of memory

    Code:
    for(int i = 0;i < 20;i++)
            delete  objectptr[i];
    delete [] objectptr;
    Nana C++ Library is a GUI framework that designed to be C++ style, cross-platform and easy-to-use.

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    127
    creating a dynamic 2-dimension array in this way is more efficiency

    Code:
    SomeClass** create(size_t x, size_t y)
    {
         if(x==0 || y==0) return 0;
    
         SomeClass* p = new SomeClass[x * y];
         return reinterpret_cast<SomeClass**>(p);
    }
    
    void destory(SomeClass** p)
    {
        delete [] reinterpret_cast<SomeClass*>(p);
    }
    Nana C++ Library is a GUI framework that designed to be C++ style, cross-platform and easy-to-use.

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Whenever you use new, you should always use delete to free up the memory when you are done using the memory. And, whenever you use 'new []', you need to use 'delete []'. What that means is: when you use "new []" to create an array, then when you delete, you use 'delete []' to delete the whole array. On the other hand, if you just use "new" to dynamically create some memory, then you just use "delete". In addition, the number of new's should equal the number of delete's.

    The reason you need brackets to delete arrays is because a pointer to an array looks like this:
    Code:
    className** p-------->className*
                          className*
                          className*
    If you only use delete, then you will only delete the first line. When you use delete[], that command is programed to delete all the memory.

    And if i do this ??

    char c = new char[20];

    delete c; // instead of delete [] c

    is it an error ??
    No. The compiler has no idea that's not what you intended. After all, you could be deleting the rest of the memory later.

    I tried also to create an array of pointers to objects and verify that delete []
    calls actually the destructors of all objects in the array before
    deleting the array itself

    In order to do that i put a printf in the class' destructor,but it wasn't displayed
    Examine the output from this program:
    Code:
    #include <iostream>
    using namespace std;
    
    class Apple
    {
    public:
    	~Apple()
    	{
    		cout<<"Apple object destroyed"<<endl;
    	}
    };
    
    int main()
    {
            Apple** ptr = new Apple*[3];
    
    	for(int i = 0; i<3; i++)
    	{
    		ptr[i] = new Apple;
    	}
    
    	for(i=0; i<3; i++)
    	{
    		delete ptr[i]; //ptr[i] does not point to an array.
    			       //ptr[i] points to a single Apple object.
    	}
    
    	delete [] ptr;
    
    
    	return 0;
    }
    
    output:
    Apple object destroyed
    Apple object destroyed
    Apple object destroyed
    Press any key to continue
    Last edited by 7stud; 05-18-2005 at 06:16 PM.

  6. #6
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    There is one major difference between delete and delete[] that hasnt been mentioned yet.
    Code:
    class X
    {
       public:
         virtual ~X() {}
    };
    
    class Y : public X
    {
       public:
         virtual ~Y(){}
    };
    
    int main()
    {
       X* array = new Y[10];
       X* obj = new Y;
       delete [] array;  // line 1
       delete obj;     // line 2
       return 0;
    }
    Is line 1 legal? whats going to happen? which destructor(s) get called?
    Is line 2 legal? whats going to happen? which destructor(s) get called?
    Why the difference? whats it all mean??
    See if you can work it out.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  7. #7
    Registered User
    Join Date
    Jun 2004
    Posts
    722
    Quote Originally Posted by Lionel
    I tried also to create an array of pointers to objects and verify that delete []
    calls actually the destructors of all objects in the array before
    deleting the array itself

    In order to do that i put a printf in the class' destructor,but it wasn't displayed
    if it wasn't displayed then the constructors haven't been called...

  8. #8
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    In the code I posted above. Line 2 is well formed and does the right thing everytime. ~Y() followed by ~X() gets called.
    On the other hand line 1 is illegal and undefined behaviour. delete[] expects that the static type passed to it matches the dynamic type of the objects you are deleting. My copy of MSVC does indeed call the right destructors in the right order but this cannot be relied upon.

    Whats it all mean. Never call delete[] thru a base class pointer if the objects you are deleting are derived objects even if the classes concerned provide virtual destructors.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Stoned_Coder, that is a direct consequence of a much simpler dictate: never treat arrays of objects polymorphically. Add a variable to X and another to Y in your example, then allocate two objects instead of one. I'd be VERY surprised indeed if that still worked.

    Using delete on something allocated with new[], or delete[] on something allocated with new, is undefined behaviour, plain and simple. Anything at all might happen that your CPU is capable of doing. On NASA's top-secret computers it triggers time travel or something.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. delete []
    By homeyg in forum C++ Programming
    Replies: 2
    Last Post: 06-02-2005, 06:21 PM
  2. delete []
    By Zahl in forum C++ Programming
    Replies: 2
    Last Post: 10-19-2002, 08:11 AM
  3. Which comes first...delete [] or NULL?
    By Waldo2k2 in forum C++ Programming
    Replies: 13
    Last Post: 08-09-2002, 09:05 AM
  4. Problem need help
    By Srpurdy in forum C++ Programming
    Replies: 1
    Last Post: 07-24-2002, 12:45 PM
  5. memory management...
    By master5001 in forum Game Programming
    Replies: 24
    Last Post: 01-07-2002, 05:50 PM