Freeing Dynamic Memory

If I do something like

1
2
  MyObject* o1=new MyObject[100];
  delete [50]o1;


Are only the first 50 MyObject destructors called?
Is the data held in MyObject for the other MyObject's still accessible somewhere or is it lost forever just taking up space at some random spot in memory now?

If I had created a new pointer and pointed it at the 50th spot and then called delete [50]o1;
what happens when I try and access the memory at that pointer?
Last edited on
Are only the first 50 MyObject destructors called?
You could always test it with an output statement in the destructor ;p
http://ideone.com/V2nq14 notice how it doesn't compile? delete [50]o1; delete[] is an operator. Are you trying to delete only the first 50 elements?
I was able to compile a little test on VS2012

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

struct Test
{
	bool boo;
	Test() : boo(true){}
	~Test(){std::cout<<"Destruct!\n";}
};

using namespace std;

int main()
{
	Test* t1 = new Test[5];
	Test*t2=t1+4;
	t2->boo=false;
	delete [3]t1;
	cout<<t2->boo;

	char a;
	cin>>a;

  return 0;
}


Which output:

Destruct!
Destruct!
Destruct!
Destruct!
254


So only part of the destructors are called, but t2 no longer points to a Test object. Does that mean there is one bool's worth of memory out there that cannot be accessed?

Edit:
Not really trying to actually do anything. More just wondering what exactly happens when delete[] is called.
Last edited on
closed account (2AoiNwbp)
I didn't know that structs could have constructors and destructor... nice test.
Why does it show 254 instead of false?
Last edited on
delete [3]t1 is not a C++ expression, you must have found some sort of Microsoft-only language extension. If so, their documentation should say what it does.
Last edited on
aabuezo wrote:
I didn't know that structs could have constructors and destructor... nice test.
Why does it show 254 instead of false?

Line 18 results in undefined behavior. t2 doesn't point to a valid object.

Cubbi wrote:
you must have found some sort of Microsoft-only language extension. If so, their documentation should say what it does.

As near as I can tell the number in the brackets is simply ignored by VC++. The OP did not portray the output accurately.
I saw an example in a book about syntax from an earlier form that it warns you might see in "old code". This book was originally published in the mid 90's so maybe that has something to do with it.

Maybe I just miscounted the first time because now calling delete []t2 with any number between the brackets calls the correct number of destructors.
Last edited on
Topic archived. No new replies allowed.