消息:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Run Code Online (Sandbox Code Playgroud)
我查看了gdb backtrace,这是我自己实现的最低级别方法:
/*
* get an array of vec3s, which will be used for rendering the image
*/
vec3 *MarchingCubes::getVertexNormalArray(){
// Used the same array size technique as getVertexArray: we want indices to match up
vec3 *array = new vec3[this->meshPoints.getNumFaces() * 3]; //3 vertices per face
int j=0;
for (unsigned int i=0; i < (this->meshPoints.getNumFaces() * 3); i++) {
realVec normal = this->meshPoints.getNormalForVertex(i);
// PCReal* iter = normal.begin();
if (normal.size() >= 3) {
array[j++] = vec3(normal[0], normal[1], normal[2]);
}
cout << i << " ";
}
return array;
}
Run Code Online (Sandbox Code Playgroud)
您在上面看到的cout语句表明它在7000次迭代后终止.上面的函数只在我的应用程序结束时调用一次.在调用上面的函数之前,我调用了一个非常相似的函数,这不会导致问题.
Mat*_*lia 24
(从评论中移动/扩展)
由于您每次都在分配一个新数组而不解除分配,因此您会发生大量内存泄漏,即您继续向系统询问内存而不会将其恢复.最终堆上的空间结束,在下一次分配时,你得到的只是一个std::bad_alloc
例外.
"C风格"的解决方案是记住在你不再需要它时释放这样的内存(delete[]
但是),这是(1)容易出错(例如,如果你在函数内有多个返回路径) (2)潜在的异常 - 不安全(如果您有异常,每条指令都会成为潜在的返回路径!).因此,应该避免这种方式.
惯用的C++解决方案是使用智能指针 - 封装指针的小对象,并在销毁时释放相关内存 - 或标准容器,它们或多或少地具有相同的功能,但具有复制语义和一些更多的铃声和口哨声(包括在其中存储数组的大小).
我在尝试分配负长度数组时遇到此错误:
double myArray = new double[-9000];
以防万一它可以帮助任何人。
我的问题原来是this->meshPoints.getNormalForVertex(i)
访问长度小于的数组(或向量,我不记得了)this->meshPoints.getNumFaces() * 3
。所以它的访问越界了。