树二进制 C/C++ 进程返回 -1073741819 (0xC0000005)

Tree Binary C/C++ Process returned -1073741819 (0xC0000005)

我是 C/C++ 编程的新手。我正在尝试编写二叉树代码并找到它的 PreOrder、PostOrder、InOrder 结构。到目前为止,我在 3 级子树上做得很好,但是当我尝试添加更多子树(4 级)时,出现 "Process returned -1073741819 (0xC0000005)" 错误。我知道这是内存分配违规,我做了一些研究但严重的是我不知道如何解决它。这是我的代码

#include <iostream>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

struct node
{
    string data;
    struct node* left;
    struct node* right;
};

/* allocates a new node with the NULL left and right pointers. */
struct node* newNode(string data)
{
    struct node* node = (struct node*)
    malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return(node);
}

/* Given the tree, print nodes, postorder traversal. */
void printPostorder(struct node* node)
{
    if (node == NULL)
    return;

    // first recur on left subtree
    printPostorder(node->left);
    // then recur on right subtree
    printPostorder(node->right);
    // now deal with the node
    // printf("%d ", node->data);
    cout << node->data;
}

/* print nodes in inorder*/
void printInorder(struct node* node)
{
    if (node == NULL)
    return;
    /* first recur on left child */
    printInorder(node->left);
    /* then print the data of node */
    // printf("%d ", node->data);
    cout << node->data;
    /* now recur on right child */
    printInorder(node->right);
}

/* print nodes in preorder*/
void printPreorder(struct node* node)
{
    if (node == NULL)
    return;
    /* first print data of node */
    // printf("%d ", node->data);
    cout << node->data;
    /* then recur on left sutree */
    printPreorder(node->left);
    /* now recur on right subtree */
    printPreorder(node->right);
}

int main()
{
    struct node *root = newNode("A");
    root->left = newNode("B");
    root->right = newNode("C");
    root->left->left = newNode("D");
    root->left->right = newNode("E");
    root->right->left = newNode("F");
    root->right->right = newNode("G");
    root->left->right->left = newNode("H");
    root->left->right->right = newNode("I");
    root->right->left->left = newNode("J"); // if i delete this, all is fine
    root->right->left->right = newNode("K"); // if i delete this, all is fine

    printf("\n Preorder traversal of binary tree is \n");
    printPreorder(root);
    printf("\n Inorder traversal of binary tree is \n");
    printInorder(root);
    printf("\n Postorder traversal of binary tree is \n");
    printPostorder(root);

    return 0;
}

抱歉我的英语不好,希望大家能理解。提前致谢:)

一个主要问题和未定义行为(可能导致崩溃)的来源是您正在使用malloc 分配您的结构。问题是它实际上并没有构造你的对象,它只是分配内存。这意味着节点中的字符串成员将无法正确构造,并导致上述 未定义行为.

分配内存时,任何类型,在 C++ 中,您应该使用 new:

node* node = new struct node;

注意:这里必须使用struct关键字,因为你有一个类型和一个同名的变量。