Skip to main content
GameDev.net gamedev.net
🔒 Locked

Destructor problem

Started by ManaStone Oct 17, 2005 at 3:20 PM 1 replies 400+ views
Original Post
ManaStone
ManaStone
I’ve spend hours upon hours trying find out what is wrong with a program I am doing and I finally narrowed it down to using a destructor with a placement new. Whenever I have a class with a destructor I always get the wrong pointer returned when I try to use a placement new on it. Here is some code that illustrates my problem:

#include <iostream>
using namespace std;


class cBlah{
private:
	int x[10];
public:
	cBlah()
	{
		for(int i=0;i<10;i++)
		{

			x=i;
		
		}

	}//end constructor
 
	~cBlah()
	{
	
	}// end destructor

};// END CLASS



int main(int argc, char** argv)
{
	
	
	cBlah *pBlah= (cBlah*) malloc(sizeof(cBlah)*3);
	cBlah *pBlah2;

	cout<<"first pointer:"<<pBlah<<endl;
	pBlah2=new(pBlah) cBlah[3];
	cout<<"second pointer:"<<pBlah2<<endl;

	return 0;
	
}

-------results--------- first pointer:00420400 second pointer:00420404 Press any key to continue ------------------------ Is there anyway around this or am I going to have to quit using destructors?
-----------------------------Download my real time 3D RPG.
Enigma
Enigma
Why are you wanting to do this? (i.e. there may be a better way, probably a std::vector with a malloc-based allocator).

The problem occurs because operator new[] and placement operator new[] are allowed to "allocate" additional memory for book-keeping information. Compilers will often store the number of elements in an array in the four bytes immediately preceeding the array, to be used when the array is deallocated to know how many destructors to call. It appears that your compiler is doing the same with placement operator new[] (which also means that it will be overwriting beyond the end of the array you malloced), but only when the class has a user-defined destructor.

Enigma
ManaStone
ManaStone
Alright, thanks for that information.
-----------------------------Download my real time 3D RPG.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.