473,387 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

allocate on the heap when using exception

Hello!

When you allocate object dynamically which mean on the heap I find that a
problem when using exception.
What is the prefer method to handle this kind of problem.

//Tony
Jul 23 '05 #1
3 2214
Tony Johansson wrote:
Hello!

When you allocate object dynamically which mean on the heap I find that a
problem when using exception.
Why?
What is the prefer method to handle this kind of problem.


It's unclear what problem you are referring to.

Jul 23 '05 #2
Tony Johansson wrote:
Hello!

When you allocate object dynamically which mean on the heap I find that a
problem when using exception.
What is the prefer method to handle this kind of problem.

//Tony


If I understand what you are asking, then you want an auto_ptr. Example:

#include <memory>

class A { ... } ;
class B { ... } ;
class C { ... } ;

....
std::auto_ptr<A> pa(new A) ;
std::auto_ptr<B> pb(new B) ;
std::auto_ptr<C> pc(new C) ;
....

When pa, pb, and pc have their destructors called, they will delete the
memory that they "own". The important part here is that pa, pb, and pc
are NOT dynamically allocated, so if an exception is thrown, you are
guaranteed that their destructors are called appropriately.

This web site gives some useful information:
http://www.gotw.ca/gotw/042.htm

One rather important thing to keep in mind is that you cannot put an
auto_ptr in a standard container (the standard containers require their
value types to be Assignable, a set of obligations which auto_ptr does
not fulfill).

-Alan
Jul 23 '05 #3

"Tony Johansson" <jo*****************@telia.com> wrote in message
news:j_*******************@newsb.telia.net...
Hello!

When you allocate object dynamically which mean on the heap I find that a
problem when using exception.
What is the prefer method to handle this kind of problem.


There is no problem, its your responsability to catch the generated
exception at the level of your choice (a failed new throws a std::bad_alloc
exception). Its also your responsability to write code that doesn't generate
memory leaks so as not to find yourself in a situation where new allocations
fail. The same goes for virtual destructors in the case inheritence is
involved (a failed allocation needs to invoke the base class d~tors).

The problem, in fact, is understanding what happens when an exception is
indeed thrown. Not catching the exception *unwinds* the present scope off
the call stack and passes the exception object up to next level. If next
scope level doesn't handle the exception, that scope is unwound and the
original exception object is passed up again. This process continues until
either the exception object is caught or an unexpected exception handler
catches it.

To explain the exception-object passing unwind mechanism, consider a class N
that throws a std::bad_alloc exception in its ctor when its member is set to
2. I'm artificially throwing a new allocation failure when N *p_n2 = new
N(2) is invoked.

Note how the last 2 objects don't get constructed and therefore never get
destroyed. Throwing the std::bad_alloc exception object mimics what happens
when the allocation actually fails at runtime.

#include <iostream>
#include <stdexcept>

class N
{
int n;
public:
N(int nn) : n(nn)
{
if (2 == n) // testing std::bad_alloc exception
{
std::cout << "ctor unwind !!!\n";
throw std::bad_alloc("std::bad_alloc exception object\n");
}
std::cout << "N ctor invoked\n";
}
~N()
{
std::cout << "N d~tor invoked\n";
}
}; // class N

int main(int argc, char* argv[])
{
N *p_n0 = 0;
N *p_n1 = 0;
N *p_n2 = 0;
N *p_n3 = 0;

try
{
p_n0 = new N(0);
p_n1 = new N(1);
p_n2 = new N(2); // will throw
p_n3 = new N(3);
}
catch(const std::bad_alloc& e)
{
std::cout << "Error: " << e.what();
}

if (0 != p_n0)
delete p_n0;
if (0 != p_n1)
delete p_n1;
if (0 != p_n2)
delete p_n2;
if (0 != p_n3)
delete p_n3;

return 0;
}

/*
N ctor invoked
N ctor invoked
ctor unwind !!!
Error: std::bad_alloc exception object
N d~tor invoked
N d~tor invoked
*/

Note how the third object (*p_n2) is never allocated and the fouth
allocation (*p_n3) is never attempted.
Now, what happens if i don't wrap the new allocations in main() in a
try-catch block? Test it.
Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Sachin Garg | last post by:
Hi, When trying to return objects of type std::list<MyClass> from my function, I get a corrupt heap. (I checked using MSVC++ 7.0 runtime heap check facility) Basically, I am creating a...
1
by: nrhayyal | last post by:
hi all, i am working on C++ on AIX machine. i am running one of my module which is built using 10+ user built libraries. i am getting St9bad_alloc exception. i came to know that this exception...
3
by: jcgeorge | last post by:
I am getting this: RETCODE : ZRC=0x8B59000D=-1957101555=SQLKF_NOMEM_BUFFER_HEAP "No memory available in 'FCMBP Heap'" DIA8300C A memory heap error has occurred. and this FUNCTION: DB2 UDB,...
9
by: gold | last post by:
Hello all, I want know abt wht kind of datastructures using both C & C++ internally. Some were said heap, others said tree anyone can explain brief?
13
by: shsingh | last post by:
I have a class A containing some map as data variables. I creat an object of class A on heap by allocatiing memory by using "malloc". This will return me the required memory but the object is not...
2
by: lovecreatesbea... | last post by:
If the built-in operator keyword new doesn't allocate memory on heap and it calls global operator new (::operator new) or class member operator new to do that. What are the two kinds of operator...
1
by: =?Utf-8?B?Tm90cmUgUG91YmVsbGU=?= | last post by:
I apologize if this question has been asked before (I imagine it has). But, I'd like a definitive response. Is it possible using C++/CLI to allocate a (normally) managed reference type on the...
2
by: jayapal | last post by:
Hi , I am using the NEW operator to allocate the memory in many places of my code.But I am not doing any error hadling or exception handling.Can any one suggests me how to do exception handling,...
11
by: Bryan Parkoff | last post by:
I want to know how much static memory is limited before execution program starts. I would write a large array. The large array has 65,536 elements. The data size is double word. The static...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.