473,765 Members | 2,059 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

throwing out of memory exception in c++ doesnt work

why does the following code not work????
after compiling and running it will just say killed after all my memory
filled up
any suggestions?
#include <iostream>
using namespace std;

void out_of_mem() {
cout << "problem\n" ;
}

// void ?
int main() {

set_new_handler (out_of_mem);

while(1) {
int * tst = new int[1024];
if (!tst)
cout << "problem\n" ;
}

Jul 22 '05 #1
21 7286
On Mon, 01 Mar 2004 03:45:44 GMT, Stephan
<st*****@frogki ng.stephas.home linux.org> wrote:
why does the following code not work????
after compiling and running it will just say killed after all my memory
filled up
any suggestions?

#include <iostream>
using namespace std;

void out_of_mem() {
cout << "problem\n" ;
}

// void ?
int main() {

set_new_handler (out_of_mem);

while(1) {
int * tst = new int[1024];
if (!tst)
cout << "problem\n" ;
}

The subject of your post is "throwing out of memory exception in c++
doesn't work", but you've done precisely what it takes to /prevent/ such an
exception from ever being thrown: you've created and installed a
new_handler that doesn't follow the rules of what a new_handler should do,
which is one of the following ( I'm plagiarizing this from Dinkumware's C++
Reference):

make more storage available for allocation and then return
call either abort() or exit(int)
throw an object of type bad_alloc

If you've got a reasonably healthy quantity of virtual memory available,
though, it may take quite a while to thrash itself to exhaustion before it
reaches the point of calling your new_handler, so let's speed things up a
bit and add some exception handling:

#include <iostream>
#include <exception>
#include <stdexcept>

using namespace std;

void out_of_mem() {
cerr << "in out_of_mem: problem\n";
throw bad_alloc();
}

int main() {

set_new_handler (out_of_mem);

try {
while(1) {
cout << "Top of loop" << endl;
int * tst = new int[800000000]; // make this too much!
if (!tst)
cout << "end of loop: problem\n";
}
}
catch (const exception &e)
{
cerr << "Caught: " << e.what() << endl;
exit(1);
}

return 0; // not likely to get here!
}
Output (MSVC 7.1):

Top of loop
in out_of_mem: problem
Caught: bad allocation
So after you "handle" the exceptions and make sure your new_handler does
one of the right things, you'll still have the virtual memory thrashing
problem to contend with. I can't help you there, but you definitely want to
do a better job of avoiding memory leaks than your test program did (yeah
yeah, just kidding), and perhaps just "know" how much memory you can
allocate before the thrashing commences and try to keep track of what
you've allocated.

Good luck,
-leor

Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #2
On Mon, 01 Mar 2004 04:30:48 +0000, Leor Zolman wrote:


The subject of your post is "throwing out of memory exception in c++
doesn't work", but you've done precisely what it takes to /prevent/ such an
exception from ever being thrown: you've created and installed a
new_handler that doesn't follow the rules of what a new_handler should do,
which is one of the following ( I'm plagiarizing this from Dinkumware's C++
Reference):

make more storage available for allocation and then return
call either abort() or exit(int)
throw an object of type bad_alloc

If you've got a reasonably healthy quantity of virtual memory available,
though, it may take quite a while to thrash itself to exhaustion before it
reaches the point of calling your new_handler, so let's speed things up a
bit and add some exception handling:

#include <iostream>
#include <exception>
#include <stdexcept>

using namespace std;

void out_of_mem() {
cerr << "in out_of_mem: problem\n";
throw bad_alloc();
}

int main() {

set_new_handler (out_of_mem);

try {
while(1) {
cout << "Top of loop" << endl;
int * tst = new int[800000000]; // make this too much!
if (!tst)
cout << "end of loop: problem\n";
}
}
catch (const exception &e)
{
cerr << "Caught: " << e.what() << endl;
exit(1);
}

return 0; // not likely to get here!
}
Output (MSVC 7.1):

Top of loop
in out_of_mem: problem
Caught: bad allocation
So after you "handle" the exceptions and make sure your new_handler does
one of the right things, you'll still have the virtual memory thrashing
problem to contend with. I can't help you there, but you definitely want to
do a better job of avoiding memory leaks than your test program did (yeah
yeah, just kidding), and perhaps just "know" how much memory you can
allocate before the thrashing commences and try to keep track of what
you've allocated.

Good luck,
-leor

Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html


thanks for the quick post!!
and your code seems to make a lot more sense now, and the exception gets
thrown, when allocating the array of ints, but I am trying to allocate a
couple small int arrays, and than it will just say Killed and I have no
ide why it didnt go into the handler.
thanks for the good try block/catch block example (although I have no idea
where the exception data type comes from, and I guess I want to avoid it?)
thx
Stephan

Jul 22 '05 #3
On Mon, 01 Mar 2004 05:12:56 GMT, Stephan
<st*****@frogki ng.stephas.home linux.org> wrote:


thanks for the quick post!!
and your code seems to make a lot more sense now, and the exception gets
thrown, when allocating the array of ints, but I am trying to allocate a
couple small int arrays, and than it will just say Killed and I have no
ide why it didnt go into the handler.
If you're not allocating much memory and your program crashes, I doubt the
crash is related to exhaustion of the free store! Pointer bug? Have a
debugger you can fire up and trace through the program with? Why do you
think the issue is dynamic-memory-allocation-failure related?
thanks for the good try block/catch block example (although I have no idea
where the exception data type comes from, and I guess I want to avoid it?)
You mean bad_alloc? That's from <stdexcept> ("Standard exceptions"). If
you're not all that familiar with the exception handling mechanism and/or
debugging techniques, I highly recommend the first few chapters of
Eckel/Allison's _Thinking in C++ Volume 2_, a free download at
www.mindview.net

Good luck,
-leor
thx
Stephan


Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #4
On Mon, 01 Mar 2004 05:41:20 +0000, Leor Zolman wrote:
On Mon, 01 Mar 2004 05:12:56 GMT, Stephan
<st*****@frogki ng.stephas.home linux.org> wrote:

If you're not allocating much memory and your program crashes, I doubt the
crash is related to exhaustion of the free store! Pointer bug? Have a
debugger you can fire up and trace through the program with? Why do you
think the issue is dynamic-memory-allocation-failure related?
gdb just tells me:
Program terminated with signal SIGKILL, Killed.
I didnt kill it and gdb doesnt report a line number, and gtkrellm shows
that my memory is filling up until the SIGKILL interrupts.
You mean bad_alloc? That's from <stdexcept> ("Standard exceptions"). If
you're not all that familiar with the exception handling mechanism
and/or debugging techniques, I highly recommend the first few chapters
of Eckel/Allison's _Thinking in C++ Volume 2_, a free download at
www.mindview.net

Good luck,
-leor
thx
Stephan
Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix C++
users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html

I am pretty familiar with the above, and I meant the actual exception data
type you wrote here: catch (const exception &e)

I think this is the type for any OS thrown exceptions, since you can throw
your own int, char, whatever ones. I guess I answered my own question.

However I am still unsure about why I get a SIGKILL ! If I leave your try
and catch block out and dont throw the bad_alloc(), I ll be stuck in an
endless loop but I can't even see that more memory is used in gtkrellm,
which shows how much memory is currently in use.
thanks
stephan
Jul 22 '05 #5
On Mon, 01 Mar 2004 06:08:18 GMT, Stephan
<st*****@frogki ng.stephas.home linux.org> wrote:
On Mon, 01 Mar 2004 05:41:20 +0000, Leor Zolman wrote:
If you're not allocating much memory and your program crashes, I doubt the
crash is related to exhaustion of the free store! Pointer bug? Have a
debugger you can fire up and trace through the program with? Why do you
think the issue is dynamic-memory-allocation-failure related?


gdb just tells me:
Program terminated with signal SIGKILL, Killed.
I didnt kill it and gdb doesnt report a line number, and gtkrellm shows
that my memory is filling up until the SIGKILL interrupts.


Good, intuitive debuggers can be hard to find on Unix...but there's always
good 'ole cerr. As a last resort I begin putting in trace statements. There
are some great tricks for doing that sort of thing in the Eckel/Allison
book I cited. You need a better handle on where the code is when it
crashes.
I am pretty familiar with the above, and I meant the actual exception data
type you wrote here:
catch (const exception &e)I think this is the type for any OS thrown exceptions, since you can throw
your own int, char, whatever ones. I guess I answered my own question.


Yeah, basically all standard exceptions derive from "exception" ; in this
case I did that to gain access to the what() member function. If I didn't
care about that, I would probably just have used catch(...)
-leor

However I am still unsure about why I get a SIGKILL ! If I leave your try
and catch block out and dont throw the bad_alloc(), I ll be stuck in an
endless loop but I can't even see that more memory is used in gtkrellm,
which shows how much memory is currently in use.
thanks
stephan


Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #6

"Leor Zolman" <le**@bdsoft.co m> wrote in message
news:kc******** *************** *********@4ax.c om...
| On Mon, 01 Mar 2004 03:45:44 GMT, Stephan
| <st*****@frogki ng.stephas.home linux.org> wrote:
|
| >why does the following code not work????
| >after compiling and running it will just say killed after all my memory
| >filled up
| >any suggestions?
| >
| >#include <iostream>
| >using namespace std;
| >
| >void out_of_mem() {
| > cout << "problem\n" ;
| >}
| >
| >// void ?
| >int main() {
| >
| > set_new_handler (out_of_mem);
| >
| > while(1) {
| > int * tst = new int[1024];
| > if (!tst)
| > cout << "problem\n" ;
| > }

[snip]

C'mon Leor :-).

You know that 'new' does not return '0' unless you tell it to:

int * tst = new ( std::nothrow )int[ 80000000 ];

Oh, and don't forget to break out of the 'if' statement.

Cheers.
Chris Val



Jul 22 '05 #7
On Tue, 2 Mar 2004 01:00:44 +1100, "Chris \( Val \)"
<ch******@bigpo nd.com.au> wrote:

"Leor Zolman" <le**@bdsoft.co m> wrote in message
news:kc******* *************** **********@4ax. com...
| On Mon, 01 Mar 2004 03:45:44 GMT, Stephan
| <st*****@frogki ng.stephas.home linux.org> wrote:
|
| >why does the following code not work????
| >after compiling and running it will just say killed after all my memory
| >filled up
| >any suggestions?
| >
| >#include <iostream>
| >using namespace std;
| >
| >void out_of_mem() {
| > cout << "problem\n" ;
| >}
| >
| >// void ?
| >int main() {
| >
| > set_new_handler (out_of_mem);
| >
| > while(1) {
| > int * tst = new int[1024];
| > if (!tst)
| > cout << "problem\n" ;
| > }

[snip]

C'mon Leor :-).

You know that 'new' does not return '0' unless you tell it to:

int * tst = new ( std::nothrow )int[ 80000000 ];
You know, I originally was going to pursue that part of it and got
completely sidetracked by the exception behavior aspects of this...so I
stopped thinking about that code after the new operation because I figured
it would never be reached! Duh. I'm still definitely on a learning curve
when it comes to my "mental checklist" of things to look out for in these
posts!
Thanks Chris,
-leor

Oh, and don't forget to break out of the 'if' statement.

Cheers.
Chris Val



Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #8

"Chris ( Val )" <ch******@bigpo nd.com.au> wrote in message
news:c1******** *****@ID-110726.news.uni-berlin.de...
|
| "Leor Zolman" <le**@bdsoft.co m> wrote in message
| news:kc******** *************** *********@4ax.c om...
| | On Mon, 01 Mar 2004 03:45:44 GMT, Stephan
| | <st*****@frogki ng.stephas.home linux.org> wrote:
| |
| | >why does the following code not work????
| | >after compiling and running it will just say killed after all my memory
| | >filled up
| | >any suggestions?
| | >
| | >#include <iostream>
| | >using namespace std;
| | >
| | >void out_of_mem() {
| | > cout << "problem\n" ;
| | >}
| | >
| | >// void ?
| | >int main() {
| | >
| | > set_new_handler (out_of_mem);
| | >
| | > while(1) {
| | > int * tst = new int[1024];
| | > if (!tst)
| | > cout << "problem\n" ;
| | > }
|
| [snip]
|
| C'mon Leor :-).
|
| You know that 'new' does not return '0' unless you tell it to:
|
| int * tst = new ( std::nothrow )int[ 80000000 ];
|
| Oh, and don't forget to break out of the 'if' statement.

Actually - I just realised, this test is wrong :-).

Even if we use the 'std::nothrow', it will no longer
throw 'std::bad_alloc ', but rather, it will return 0,
and this will bypass 'std::set_new_h andler'.

Better to avoid the 'if' expression completely, and
redesign the test case :-).

# include <iostream>
# include <ostream>
# include <new>

void MyHandler()
{
std::cout << "MyHandler Called... " << std::endl;
throw std::bad_alloc( );
}

int main()
{
std::set_new_ha ndler( MyHandler );

try
{
for( int Idx( 0 ); Idx < 1000000; ++Idx )
new char[ Idx * Idx ];
}
catch( const std::bad_alloc& e )
{
std::cout << e.what() << std::endl;
}

std::cin.get();
return 0;
}

Cheers.
Chris Val
Jul 22 '05 #9

"Leor Zolman" <le**@bdsoft.co m> wrote in message
news:kp******** *************** *********@4ax.c om...
| On Tue, 2 Mar 2004 01:00:44 +1100, "Chris \( Val \)"
| <ch******@bigpo nd.com.au> wrote:

[snip]

| >int * tst = new ( std::nothrow )int[ 80000000 ];
|
| You know, I originally was going to pursue that part of it and got
| completely sidetracked by the exception behavior aspects of this...so I
| stopped thinking about that code after the new operation because I figured
| it would never be reached! Duh. I'm still definitely on a learning curve
| when it comes to my "mental checklist" of things to look out for in these
| posts!

I know the feeling, I feel like that now - need serious shut eye :-).

Cheers.
Chris Val
Jul 22 '05 #10

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

Similar topics

5
4682
by: Mark Oueis | last post by:
I've been struggling with this question for a while. What is better design? To design functions to return error codes when an error occures, or to have them throw exceptions. If you chose the former, i have a few questions that need to be answered. 1) What about functions that need to return a value regardless of the error. How can they also return an error code unless the function has "output" parameters. This seems messy and...
3
5068
by: Scott Brady Drummonds | last post by:
Hi, all, I've a fairly small piece of code that is causing me problems. I'm using std::string and am building a string of several dozen characters using several of std::string's functions: a blank constructor, operator=, and operator+=. This sequence of function calls causes a crash either at the call to operator+= or when the string object leaves scope (which must be the result of the destructor). Specifically, my Windows-based...
40
13530
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
13
2066
by: Jacek Dziedzic | last post by:
Hi! <OT, background> I am in a situation where I use two compilers from different vendors to compile my program. It seems that recently, due to a misconfiguration, library conflict or my ignorance, with one of the compilers I am having trouble related to libuwind.so, which, to my knowledge, deals with the intricacies of unwinding the stack upon an exception. Executables compiled with this compiler crash with a SEGV after throw(), never...
40
36115
by: Sek | last post by:
Is it appropriate to throw exception from a constructor? Thats the only way i could think of to denote the failure of constructor, wherein i am invoking couple of other classes to initialise the object. TIA Sek
0
1748
by: bcutting | last post by:
I have the following snippet of code which which makes a call into a dll to generate an array of bytes. Its arguments are a IntPtr to the bitmap, a number, and a reference to the array that it will output. -- Start DLL code snippet private static extern unsafe Int16 GetHash(IntPtr Bitmap1, Int16 FilterNum, void* ImageHash); /// <summary> /// Creates an hash using the pointer to the image bitmap
6
3565
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows uncaught exception. How to catch an exception that happened before main() try { ... } catch (...) { ... } block? Is there a way?
6
1527
by: Cucumber | last post by:
This has bugged me for some time now, and I havent have the time to discuss it before, so guys please tell me what you think. We all know we can use smart pointers in C++ to take charge of automatic deallocation of objects created in the heap, we know the smart pointer will save the address allocated with "new", and that smart pointers will call "delete" when going out of scope: ... SmartPointer< Foo > foo = new Foo(); ... ...
9
5834
by: thagor2008 | last post by:
Is the behaviour of throwing exceptions in a unix signal handler defined? eg: void sighandler(int sig) { ... do something throw myobj; }
0
9568
marktang
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...
0
9399
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,...
0
10007
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 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...
1
9957
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8832
agi2029
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...
0
5276
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...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
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.