做了个动态数组,释放时崩溃?其中调用了qsort

cfvmario cfvmario 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
写了一个程序,功能已经实现了,然而在最后释放时崩溃了,百思不得其解
程序结构是这样的:


struct Node { /* 此处没有指针成员 */ };

class NodeList // Node的动态数组
{
private:
Node *nodes;
int capacity;
int length;
public:
NodeList()
{
nodes = new Node[256];
memset(nodes, 0, 256*sizeof(Node));
capacity = 256;
length = 0;
}
int GetLength() { return length; }
Node* GetNextNode() //用此函数进行添加Node操作,必要时扩展存储空间
{
if (length == capacity)
{
capacity <<= 1;
cout << "Increasing capacity to " << capacity << "...";
Node *temp = new Node[capacity];
memcpy(temp, nodes, length*sizeof(Node) );
delete []nodes;
nodes = temp;
cout << "Complete\n";
}
return &nodes[length++];
}

Node& operator[](int i) const { return nodes[i]; }

~NodeList()
{
//delete []nodes; //按说应该有这句的,但无论有没有,程序都崩溃。本来期望注释掉这句的话,无非是个内存泄露,而内存泄露在main函数执行完时才会检测到,至少在return 0时下断点应该能断到。然而仍然是没断到就崩溃了
}
};

class Solver
{
private:
NodeList nodes;
int front;
bool tag;
public:
Solver(InputFunc f);
void Solve();
~Solver(void);
};

void Solver::Solve() //函数中涉及指针操作的只有以下片段
{
...
Node temp;
...
Node* n = nodes.GetNextNode();
memcpy(n, &temp, sizeof(Node));
...
int len = nodes.GetLength();
qsort(&nodes[front], len-front, sizeof(Node), CompareNode); //目前认为疑点在这里,front肯定没越界,不然早就里面崩了
...
}

int _tmain(int argc, _TCHAR* argv[])
{
Solver *solver = new Solver(InputBoard);
solver->Solve();
delete solver; //崩溃:corruption of heap什么的
return 0;
}

因为本来就没用到什么指针,所以感觉疑点最可能就在qsort里了。难道是qsort交换了指针指向的数据,导致delete时出错?
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
cfvmario
C++ 语言 65,214 成员 250,514 内容