在 C 程序中查找堆损坏
Find Heap Corruption In C Program
我环顾四周,但这里的大部分答案都是针对从代码中可以明显看出堆损坏的问题,或者提问者已经确定来源的问题。
我有一个 C 程序(模拟赛车)为链表动态分配内存。然后,它根据节点中的值将列表中一个或多个节点的值复制到动态分配的二维数组中。每个节点在复制后被释放,并更新链表头。重复此过程,直到列表中不再有节点(比赛结束)。
指向数组的指针返回到 main 并存储在 3D 数组中。
然后重复整个过程(新链表,新数组)。
在第二次迭代(第二场比赛)结束时,我收到堆损坏错误,我无法弄清楚是什么原因造成的。
我尝试按照此处的建议使用 VLD:Memory allocation / Heap corruption in std::string constructor
但是在包含 VLD 的情况下我没有收到错误。
我还尝试启用调试堆函数:https://msdn.microsoft.com/en-us/library/x98tx3cf.aspx
这告诉我地址是 0x596EBC5C,它似乎不包含我分配的任何内容,所以我不确定这是否有意义。
据我所知,我在这段代码中遇到了错误,但我什至不确定,我不知道这将如何帮助我找到问题的根源.
void MoveFinishers(NODE **racehead, int **FinisherList, int raceLength) {
static int numberOfFinishers = 0;
NODE *head = *racehead;
NODE *temp = *racehead;
NODE *tempNext = NULL;
while (head != NULL && head->car.distance >= raceLength)
{
FinisherList[0][numberOfFinishers] = head->car.number;
numberOfFinishers++;
head = head->next; //advance to the next finisher
}
*racehead = head; //change the list head to start with the first non-finisher
//free all list elements before the first non-finisher
while (temp != head)
{
tempNext = temp->next; //iterates through the temp values
free(temp);
temp = tempNext;
} //end while
}
我终于明白了。不幸的是,我仍然无法通过调试器找到问题,只能查看代码。
无论如何,问题在于:
static int numberOfFinishers = 0
我将其声明为静态的,因为我需要它在单场比赛中保持状态。
然而,在第一场比赛之后,我并没有重置计数器,所以这实际上是开始在未分配的内存中存储值:
FinisherList[0][numberOfFinishers]
修复非常简单,只需将其添加到函数末尾即可:
if (!head)
{
numberOfFinishers = 0;
}
我环顾四周,但这里的大部分答案都是针对从代码中可以明显看出堆损坏的问题,或者提问者已经确定来源的问题。
我有一个 C 程序(模拟赛车)为链表动态分配内存。然后,它根据节点中的值将列表中一个或多个节点的值复制到动态分配的二维数组中。每个节点在复制后被释放,并更新链表头。重复此过程,直到列表中不再有节点(比赛结束)。
指向数组的指针返回到 main 并存储在 3D 数组中。
然后重复整个过程(新链表,新数组)。
在第二次迭代(第二场比赛)结束时,我收到堆损坏错误,我无法弄清楚是什么原因造成的。
我尝试按照此处的建议使用 VLD:Memory allocation / Heap corruption in std::string constructor
但是在包含 VLD 的情况下我没有收到错误。
我还尝试启用调试堆函数:https://msdn.microsoft.com/en-us/library/x98tx3cf.aspx
这告诉我地址是 0x596EBC5C,它似乎不包含我分配的任何内容,所以我不确定这是否有意义。
据我所知,我在这段代码中遇到了错误,但我什至不确定,我不知道这将如何帮助我找到问题的根源.
void MoveFinishers(NODE **racehead, int **FinisherList, int raceLength) {
static int numberOfFinishers = 0;
NODE *head = *racehead;
NODE *temp = *racehead;
NODE *tempNext = NULL;
while (head != NULL && head->car.distance >= raceLength)
{
FinisherList[0][numberOfFinishers] = head->car.number;
numberOfFinishers++;
head = head->next; //advance to the next finisher
}
*racehead = head; //change the list head to start with the first non-finisher
//free all list elements before the first non-finisher
while (temp != head)
{
tempNext = temp->next; //iterates through the temp values
free(temp);
temp = tempNext;
} //end while
}
我终于明白了。不幸的是,我仍然无法通过调试器找到问题,只能查看代码。
无论如何,问题在于:
static int numberOfFinishers = 0
我将其声明为静态的,因为我需要它在单场比赛中保持状态。
然而,在第一场比赛之后,我并没有重置计数器,所以这实际上是开始在未分配的内存中存储值:
FinisherList[0][numberOfFinishers]
修复非常简单,只需将其添加到函数末尾即可:
if (!head)
{
numberOfFinishers = 0;
}