Mac中的分段错误,但其他在线编译器则没有

时间:2019-02-12 04:50:36

标签: c++ macos

此代码可在ideone和其他编译器上运行,但在我的mac或某些垃圾值中给出了分段错误。请帮忙。这是顺序遍历的标准方法,应该只打印1到7。

https://ideone.com/l5tkks

#include <bits/stdc++.h>
using namespace std;

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

typedef struct node* Node;

Node insert(Node root, int num){
    if(root==NULL){
        Node newNode=(Node)malloc(sizeof(Node));
        newNode->data=num;
        newNode->left=NULL;
        newNode->right=NULL;
        return newNode;
    }

    if(root->data>num)
        root->left=insert(root->left,num);
    else
        root->right=insert(root->right,num);
    return root;
}

void printinorder(Node root){
    if(root==NULL)
        return;

    printinorder(root->left);
    cout<<root->data<<endl;
    printinorder(root->right);
}

int main(){
    Node tree=NULL;
    tree=insert(tree,1);
    tree=insert(tree,2);
    tree=insert(tree,3);
    tree=insert(tree,4);
    tree=insert(tree,5);
    tree=insert(tree,6);
    tree=insert(tree,7);
    printinorder(tree);
}

1 个答案:

答案 0 :(得分:5)

Node newNode = (Node) malloc(sizeof(Node));

应该是

Node newNode = (Node) malloc(sizeof(node));