Memory Allocation Problem.

Hey all.

1
2
3
4
5
6
7
8
9
10
11
12
13

void lap::Matrix::allocMemory(){

    std::cout << "allocating...";
    try{
        matArray = new double[numRows*numCols];
    }
    catch(std::bad_alloc e)
    {
        std::cout << "ending with bad_alloc" << std::endl;
    }
    std::cout << "done!" << std::endl;
}


Program is terminating when trying to allocate memory. No exception is being caught - why not?
Last edited on
Can you show a little more of the code? Y'now, like the place you declared matArray? Maybe there's a logic error somewhere else
When I run it in the debugger it catches the exception, but when I run it normally it doesn't catch the exception & just terminates.
closed account (3hM2Nwbp)
I assume you're using visual studio - is the option to "Enable C++ Exceptions" checked?

(If you're not using Visual Studio, which IDE?)
Codeblocks. I'm compiling this as a static library...
closed account (3hM2Nwbp)
NickPaul wrote:
Codeblocks.


What compiler?

Another question: Where are numRows and numCols initialised / assigned a value?
Last edited on
GNU GCC Compiler - sorry should have stated that. This is really playing with my head. Nick
Last edited on
closed account (3hM2Nwbp)
I'm not sure what the maximum value that you can use as a subscript for an array in C++ is, but if the numRows and numCols varaibles aren't initialised, you may be trying to allocate a negative value (if you've overflowed the subscript type). I'll see how many bits your subscript can be.

*Edit - it appears the general consensus is that your system's size_t limit is the limit for array subscripts.

Try printing out the product of numRows*numCols so you can actually see what you're trying to allocate.
Last edited on
numRows*numCols = 3 when program crashes. But before I look into that problem I really want to figure out why I'm not catching the exception when running the program but do catch the exception when running it using the debugger (Codeblocks debugger).
Ok solved the bad_alloc problem. I was passing a pointer to an array whose dimensions were smaller than the function believed. So the function was accessing memory outside the bounds and writing doubles. Not sure why this lead to bad_alloc later in the program... I'll also assume it was stuffing up the exception throw/catch.

Thanks for all your help!

Nick.
Last edited on
Topic archived. No new replies allowed.