Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic allocation

Status
Not open for further replies.

joeGrammar

Programmer
Jun 4, 2001
162
CA
Check out this piece of code, This is producing memory faults upon the end of my program


void DeleteAllElements()
{
STD_NAMESPACE for_each(vector<T*>::begin(), vector<T*>::end(),
---> delete_function() );
}


This is the delete_function()

bool operator() (T * const & x) const
{ delete(x);

return true;
}

As you can see there is no checking whether the &quot;x&quot; is allocated dynamically or not, it just goes ahead and deletes it, now 90% of the time it is, but its those few times where its trying to delete something that is not and it crashes.

MY QUESTION:

Is there a way to test if something is dynamically allocated before you delete it?
 
Not really; if you want a full discussion of the issues read Scott Meyer's Effective C++. At the best you can supposedly try something like

int i;
int* pi = new int;
if (pi>&i) delete pi;

which might work under Windows as long as you only have one thread and one heap. int i; should be at the beginning of your program since the stack grows downwards. Better to make sure you only have objects on the heap in your vector...

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top