繁体   English   中英

C ++二进制树可在CentOS 6中运行,但不能在Mac OSX Mavericks中运行

[英]C++ Binary Tree Works in CentOS 6 but not Mac OSX Mavericks

现在,我对为什么以下程序在我的CentOS 6机器上看起来能正常工作感到困惑,但是在Mac OSX上运行编译的程序会导致Seg Fault 11。 我使用Eclipse和gdb调试器在Macbook上进行调试,结果有些奇怪。 这是一个简单的二叉树示例:

#include <iostream>
#include <stdlib.h>

#include "binary_tree.h"

using namespace std;

struct node* newNode(int x) {
        struct node *n = (struct node*)malloc(sizeof(struct node*));
        n->x = x;
        n->left = NULL;
        n->right = NULL;

        return n;
}

struct node* insert(struct node *node, int x) {
        if(node == NULL) {
                return newNode(x);
        } else {
                if(x <= node->x) {
                        node->left = insert(node->left, x);
                        cout << "INSERTED " << x << " LEFT OF " << node->x << endl;
                } else {
                        node->right = insert(node->right, x);
                        cout << "INSERTED " << x << " RIGHT OF " << node->x << endl;
                }

                return node;
        }
}

int main(void) {
        //Pointer to root node
        struct node *root = NULL;

        root = insert(root,4);
        root = insert(root,2);
        root = insert(root,3);
        root = insert(root,5);
        root = insert(root,1);
        root = insert(root,7);

        return 0;
}

和头文件:

/*
 * binary_tree.h
 *
 *  Created on: Jul 12, 2014
 *      Author: ccravens
 */

#ifndef BINARY_TREE_H_
#define BINARY_TREE_H_

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

#endif /* BINARY_TREE_H_ */

任何提示表示赞赏,谢谢!

这行:

struct node *n = (struct node*)malloc(sizeof(struct node*));

应该:

struct node *n = (struct node*)malloc(sizeof(struct node));

您正在分配一个指针(8个字节),而不是一个结构节点(24个字节)。 通过在valgrind(www.valgrind.org)下执行程序,很容易发现此类问题。

暂无
暂无

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

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