我有一个表示数组的类,持有指向我的其他类对象的指针。
#include "Edge.h"
class Array
{
private:
Edge** _headPtr;
int arraySize;
public:
Array(int);
void pushBack(Edge*);
// other functions...
};
Array::Array(int arraySize)
{
this->arraySize = arraySize;
this->_headPtr = new Edge*[arraySize];
}
程序调用后总是返回内存分配错误
// inserts an element on the end of the array
void Array::pushBack(Edge* element)
{
if (arraySize == 0) {
_headPtr = new Edge*[1];
_headPtr[0] = element;
arraySize++;
}
else {
Edge** _tempPtr = new Edge*[arraySize + 1]; // crashing here
memcpy(_tempPtr, _headPtr, arraySize * sizeof(Edge*));
//for (int i = 0; i < arraySize; i++) delete _headPtr[i];
delete[] _headPtr;
_tempPtr[arraySize] = element;
_headPtr = _tempPtr;
arraySize++;
}
}
我已经注释掉了该for (int i = 0; i < arraySize; i++) delete _headPtr[i];
部分,因为它导致了_free_dbg(block, _UNKNOWN_BLOCK);
错误。
从我在这里的其他问题中发现的内容来看,我想我对指向类对象的指针的动态数组的理解一定存在缺陷,但是在花了很多时间试图解决这个问题之后,我已经没有想法了。
我的程序的总体思路是对某些图算法执行时间效率测量,这是 Prim 算法实现的一部分。
导致这种情况的调用堆栈如下所示:
BinaryHeap queue = BinaryHeap();
queue.addNewElement(new Edge(v, v2, edgeWeight));
which looks like this
void BinaryHeap::addNewElement(Edge* element)
{
heapElements->pushBack(element);
heapFix_UP(heapElements->getSize()-1);
}
And finally pushBack method.
heapElements
是Array* heapElements
的二叉堆类,以初始化内部
heapElements = new Array();
BinaryHeap中构造。
Edge 是一个非常简单的类,它只包含三个整数值。
请不要建议使用 std::vector,整个想法是不要使用 STL。
好的,我找到了解决方案。上面的所有代码都运行良好,该错误在我的代码中位于完全不同的位置。
有什么问题导致整个程序在很多行之后崩溃?
这:
int** graphMatrix;
graphMatrix = new int*[vertex];
for (i = 0; i < edges; i++) graphMatrix[i] = new int[edges];
如此简单,却如此有害。
它是我的关联矩阵实现的一部分。现在所有崩溃的原因很明显 - 尝试写入/读取未分配的内存并导致堆损坏。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句