繁体   English   中英

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

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

我在C / C ++编程中很新。 我正在尝试编写二叉树代码,并找到其PreOrder,PostOrder,InOrder结构。 到目前为止,我对3级子树做得很好,但是当我尝试添加更多子级(4级)时,我收到“进程返回-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关键字,因为您有一个类型和一个具有相同名称的变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM