473,897 Members | 3,371 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

allocate on the heap when using exception


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.

Jul 23 '05 #1
3 2264
Tony Johansson wrote:

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.

It's unclear what problem you are referring to.

Jul 23 '05 #2
Tony Johansson wrote:

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.


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:

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).

Jul 23 '05 #3

"Tony Johansson" <jo************ *****@telia.com > wrote in message
news:j_******** ***********@new sb.telia.net...

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;
N(int nn) : n(nn)
if (2 == n) // testing std::bad_alloc exception
std::cout << "ctor unwind !!!\n";
throw std::bad_alloc( "std::bad_a lloc exception object\n");
std::cout << "N ctor invoked\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;

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

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 local object
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 is thrown because the heap is exhausted. when i checked while running the program , i found that the program uses 128 MB of heap after which it waits , then it throws this exception.
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, fast comm manager, sqlkfResrcFreeMemCheck, probe:100 MESSAGE : Shared mem. set is not big enough for more FCM buffers. Cur size: 297598976, Max size: 320307200, Needed size: 437059584
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?
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 initialized properly as constructor same is not get called ( as per the behavior). How to call a constructor explicitly if we want to allocate memory using malloc ?
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 new used to allocate heap memory? Before there aren't global and member operator new, the built-in operator keyword new does really allocate heap memory, right?
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 native heap? That is, instead of using gcnew, and being subject to garabage collection, could I use a native memory allocation routine like new(), with the result being that the object is created on the native heap and not known by the garbage...
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, which code part I have to add to do the exception handling Thanks in advance, ..
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 memory would allocate 256K. The 256K is a fixed memory size. After the compiler has completed compiling header and source code, the execution program might fail to run or crash. The operating system might do not display error message saying,...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.