When can a memory leak occur?

One likely reason within your description is that you try to allocate a block of some unreasonably big size because of an error in your code. Something like this;

 size_t numberOfElements;//uninitialized
 if( .... ) {
    numberOfElements = obtain();
 }
 elements = new Element[numberOfElements];

now if numberOfElements is left uninitialized it can contain some unreasonably big number and so you effectively try to allocate a block of say 3GB which the memory manager refuses to do.

So it can be not that your program is short on memory, but that it tries to allocate more memory than it could possibly be allowed to under even the best condition.


Check the profile of other processes on the machine using Process Explorer from sysinternals - you will get bad_alloc if memory is short, even if it's not you that's causing memory pressure.

Check your own memory usage using umdh to get snapshots and compare usage profile over time. You'll have to do this early in the cycle to avoid blowing up the tool, but if your process's behaviour is not degrading over time (ie. no sudden pathological behaviour) you should get accurate info on its memory usage at time T vs time T+t.


bad_alloc doesn't necessarily mean there is not enough memory. The allocation functions might also fail because the heap is corrupted. You might have some buffer overrun or code writing into deleted memory, etc.

You could also use Valgrind or one of its Windows replacements to find the leak/overrun.


Just a hunch,

But I have had trouble in the past when allocating arrays as so

int array1[SIZE];  // SIZE limited by COMPILER to the size of the stack frame

when SIZE is a large number.

The solution was to allocate with the new operator

int* array2 = new int[SIZE];  // SIZE limited only by OS/Hardware

I found this very confusing, the reason turned out to be the stack frame as discussed here in the solution by Martin York: Is there a max array length limit in C++?

All the best,

Tom