【发布时间】:2019-11-12 18:19:06
【问题描述】:
我正在尝试制作一个程序来试验 malloc 链表。 I keep getting this error。它说:
调试断言失败!
程序:...ource\repos\ConsoleApplication1\Debug\ConsoleApplication1.exe
文件:minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
线路:904
表达式:_CrtlsValidHeapPointer(block)
这是我的代码:
#include <stdio.h>
#include <corecrt_malloc.h>
#include <cstddef>
struct node_t {
int value;
struct node_t* next;
};
void printList(node_t* headNode) {
node_t* currentNode;
currentNode = headNode;
while ((currentNode->next) != NULL) {
printf("%d, ", currentNode->value);
currentNode = currentNode->next;
}
printf("%d", currentNode->value);
currentNode = currentNode->next;
}
void addNode(node_t* headNode, int nodeValue) {
node_t* currentNode = headNode;
node_t* tempNode = headNode;
while ((currentNode->next) != NULL) {
currentNode = currentNode->next;
tempNode = currentNode;
}
currentNode = (node_t*)(malloc(sizeof(node_t)));
currentNode->value = nodeValue;
tempNode->next = currentNode;
currentNode->next = NULL;
}
void popHead(node_t* headNode) {
node_t* newHead = headNode->next;
free(headNode);
headNode = newHead;
}
void freeAllNodes(node_t* headNode) {
node_t* currentHead;
node_t* tempNode;
currentHead = headNode->next;
free(headNode);
while ((currentHead->next) != NULL) {
tempNode = currentHead;
currentHead = tempNode->next;
free(tempNode);
}
free(currentHead);
}
int main()
{
node_t* nextNode;
node_t* tempNode;
node_t* headNode;
headNode = (node_t*)(malloc(sizeof(node_t)));
headNode->value = 1;
headNode->next = NULL;
printList(headNode);
printf("\n");
addNode(headNode, 2);
printList(headNode);
printf("\n");
addNode(headNode, 3);
printList(headNode);
printf("\n");
popHead(headNode);
freeAllNodes(headNode);
return 0;
}
我相信问题出在 Pop Head 上
注意:我不使用“new”和“delete”的原因是因为我希望它尽可能接近常规 c。
【问题讨论】:
-
按重试并检查调用堆栈。
-
headNode = (node_t*)(malloc(sizeof(node_t)));为什么? -
将
Stack Frame(在工具栏上)切换回您的代码,看看发生这种情况时正在执行什么。 -
您提供的代码本质上是 C,而不是 C++。如果你要将它编译为 C++,你应该使用它 - 构造函数,
new,delete,std::cout,等等。
标签: c++