Hello.
I have been writing some numerical linear algebra programs and, when declaring dynamic arrays, I have been using the check for new returning NULL. I have posted a small sample standalone program at the following link:
http://www3.telus.net/thothworks/mulmatvec0.html
(I am presently using Microsoftâs Visual C++ version 6 on a Windows 2000 computer. And, yes, I have Ivor Hortonâs book, âBeginning Visual C++ 6â)
If you view the code, you will see (lines 80 â 95) that to dynamically create an N X N array A, I first allocate space for the pointers to the rows of A. Then I allocate space for the pointers to columns for each of those rows. If new returns NULL at any time, I then have to âretrace my stepsâ: de-allocate the column space that has already been defined, then deallocate row space that has been defined. When several dynamic matrices or vectors are used in a program, this process becomes extremely onerousâif a NULL result is returned for any succeeding allocation attempt, the amount of memory that has to be deallocated becomes greater with each step.
I am now trying to upgrade my code, so I have several questions:
1) I have been told that the practice of checking new for a NULL return is a feature of Visual C++ version 6, but is not good coding practice, so should be discouraged. A better way is to use a try-catch pair to check for exceptions. So my question is: What is the oldest version of Visual C++ that supports exception checking when creating dynamic arrays (does Visual C++ version 7 support it? Or Visual C++ 2005)?
2) Assuming I upgrade my Visual C++ to a version that supports throwing exceptions when declaring dynamic arrays, how do I code the dynamic allocation such that I know exactly which allocation failed? For example, say a user wants to use a 10000X10000 array but no more memory can be found as the program is allocating space for column 8888. Normally, I would then release all memory allocated for columns 1 â 8887, all the rows, etc. However, if I wrap all dynamic memory allocation in try braces (say, lines 81 â 115 in my example program), all I know is that an exception occurred
somewhere in the try section, but I wouldnât know how much memory to deallocate before outputting an error message and terminating the program. For all I know, the exception may have occurred when trying to allocate space for the b1 or b2 vectors. So, how do I code a try-catch pair such that I know exactly where the exception occurred?
3) At the end of the program, all memory is deallocated as usual, so lines 156 â 161 of the present program would not change at all. Is this assumption correct?
Any suggestions/help/pointers to tutorials/etc. are most appreciated.
-- Duncan