The cout statement you see above indicates that it terminates after 7000+ iterations.
The above function is called only once near the end of my application. I call a very similar function before calling the above, that doesn't cause problems.

Do you ever free the arrays returned by this function with delete[]?
–
Matteo ItaliaDec 4 '11 at 21:42

1

How large is meshPoints.getNumFaces()? And how large is vec3?
–
celtschkDec 4 '11 at 21:43

6

Ouch, then you have massive memory leaks. By the way, you should use smart pointers or standard containers; you should avoid completely manual memory management in C++, your code will not be exception safe and you will always risk memory leaks.
–
Matteo ItaliaDec 4 '11 at 21:47

1

You shouldn't delete the array before it is returned, you should delete it when it is no longer needed. That is, somewhere in the code calling the function. Think of it as a blackboard: You write data on the blackboard, but you never wipe the blackboard to make place for new data (delete[]). If you do that long enough, at some time there's no place left on the blackboard. But you shouldn't wipe stuff from the blackboard which you still need; only stuff which is no longer needed.
–
celtschkDec 4 '11 at 22:07

2

Another idea, in a completely different direction: Did you check that j always stays below meshPoint.getNumFaces()*3? Maybe you get the bad_alloc due to a buffer overrun overwriting essential heap structures.
–
celtschkDec 4 '11 at 22:22

2 Answers
2

Since you are allocating a new array every time without deallocating it, you have a massive memory leak, i.e. you continue to ask memory to the system without ever giving it back. Eventually the space on the heap finishes, and at the next allocation all you get is a std::bad_alloc exception.

The "C-style" solution would be to remember to deallocate such memory when you don't need it anymore (with delete[]), but, this is (1) error-prone (think e.g. if you have multiple return paths inside a function) and (2) potentially exception-unsafe (every instruction becomes a potential return path if you have exceptions!). Thus, this way should be avoided.

The idiomatic C++ solution is to use either smart pointers - small objects that encapsulate the pointer and deallocate the associated memory when they are destroyed - or standard containers, that do more or less the same thing but with copy semantics and some more bells and whistles (including storing the size of the array inside them).

My problem turned out to be that this->meshPoints.getNormalForVertex(i) accesses an array (or vector, I can't remember) whose length is less than this->meshPoints.getNumFaces() * 3. So it was accessing out of bounds.