Tree Binary C / C ++进程返回-1073741819(0xC0000005)

时间:2015-09-03 08:58:41

标签: c++ segmentation-fault

我是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;
}

抱歉我的英文不好,希望大家都明白。并提前感谢:)

1 个答案:

答案 0 :(得分:6)

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

在C ++中分配内存的任何时,你应该使用new

node* node = new struct node;

注意:您必须在此使用struct关键字,因为您的类型和变量具有相同的名称。