【问题标题】:Visual Studio 2019 Debug assertion failedVisual Studio 2019 调试断言失败
【发布时间】: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++,你应该使用它 - 构造函数,newdeletestd::cout,等等。

标签: c++


【解决方案1】:

popHead 中的 headNode = newHead 赋值是赋值给本地的 headNode 变量。此更改不会传递回调用者。结果是当您调用freeAllNodes 时,您将尝试再次释放此头节点。

可能的解决方案包括将头节点作为引用传递(void popHead(node_t *&amp;headNode)) 或返回新的头节点指针(node_t *popHead(node_t *headNode) { ... return headNode; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2014-09-09
    • 2016-04-21
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多