Archived

This topic is now archived and is closed to further replies.

Jaggy

memory clear-up and vector arrays

Recommended Posts

Hi - I am new to using vectors as an array. They seem to be pretty good - my only question is when I have something like this:
		for( int i = 0; i < m_BlocksInWorld; i++)
		{
			cBlock* thisBlock;
			thisBlock = new cBlock(m_Display);
			
			// Load the info into this block

			thisBlock->loadBlocks(File);

			// Add it to the array

			m_Blocks.push_back(thisBlock);

			// Draw it on screen

			thisBlock->drawBlock();
		}
I am creating a 'new' cBlock each loop - do I ever have to delete these or will my vector handle all that now? Here is my clean-up code, please let me know if I'm missing anything or something here is unnecessary:
        for(int i = 0; i < m_BlocksInWorld; i++)
	{
		// Loop through each block and erase it

		m_Blocks[i]->clearBlock(m_bg);
		m_Blocks[i] = NULL;
	}
	m_Blocks.clear();
	m_Blocks.resize(0);
	m_BlocksInWorld = 0;
In that loop I tried a
 delete m_Blocks[i] 
, but that caused a crash. Thanks for reading my question I know it's not a critical question but hopefully you can appreciate I'm trying to tidy up memory behind me Edit: cries at the html gobbling up his tags Edit2: More crying [edited by - jaggy on April 21, 2004 10:56:01 AM]

Share this post


Link to post
Share on other sites
Yes, you will indeed need to call delete on them. Vectors won''t do it for you.

STL vectors (and lists, stacks, etc...) only handle their own memory. The vector contains a list of pointers to blocks, but really, all it''s concerned about is that it contains a list of 4-byte elements. It allocates memory to store those 4-byte elements. When it gets destroyed, it deallocates the memory for those 4-byte elements. The fact that those elements are actually pointers that point to memory that you allocated don''t concern it. Thus, you need to delete everything you new.

The reason delete caused a crashed is probably because the pointer was no longer valid, for one reason or another. But you certainly need to call delete. The problem isn''t with the vector itself, but with something else in code, causing some of the pointers within the vector to be invalid at the point when you try to delete them.

Share this post


Link to post
Share on other sites
Thanks very much for your very clear response - I understand what I have to do with them now.

I found out why it was erroring too - I was deleting the pointer to the display object in the block''s deconstructor. So of course it would remove the first block fine, and then error for the other blocks because I had already destroyed the pointer...duh

Share this post


Link to post
Share on other sites