Saturday, September 10, 2011

dynamic memory exception

Weekly tips collect by CS435 classmates:
by Dylan Sawyer
(1) When the normal new operator is used to create something (this whole new thing is the cue, the keyword, for dynamic memory), if that something that is in the process of being created does not have enough memory available, then it throws an exception. This is typically bad, as it will, in most cases, cause an abrupt termination of your program (leaving the user with a bitter aftertaste of disgust, or rage if said user is the programmer). Of course, handling such possibilities must be done to keep things running smoothly.

(2) If you don't want to deal with that kind of thing, then there is another possibility: nothrow. When writing a statement involving new

dude = new thing

it could instead be written as

dude = new (nothrow) thing

This will cause the pointer (dude in this case) to point to null if there is a lack of memory available. This is another alternative to throwing exceptions (using a keyword called nothrow... go figure). This delays the aftertaste a little.

Fountain of C++ Knowledge:

reply by Gordie:

The whole memory allocation process is rather confusing, especially when the thing being created is an object and part of the "new"-ing process is a call to a constructor method that can also throw an exception because it tries to do something illegal.

A couple of lessons come from this:
- do not do much in your constructors; instead, do safe things in your constructor and if you need to do dangerous things have another routine (Initialize() or something like that) that must be called after creation.
- take a look at exceptions (try, catch, etc.) and wrap dangerous pieces of code that may cause memory errors.

A piece of advice that I have found very useful came from a rather expert driver developer at ATI. His quote was related directly to allocating memory and protecting against not having enough: "if we can't allocate that amount of memory we have bigger problems."  Really, this just means that if ordinary allocations (relatively small) are going to fail then there is something else seriously wrong with the system--worry about the big allocations.

No comments:

Post a Comment