C ++二进制树在CentOS 6中运行,但不适用于Mac OSX Mavericks

时间:2014-07-13 23:21:46

标签: c++ macos centos

现在,我很惊讶为什么以下程序在我的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_ */

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

1 个答案:

答案 0 :(得分:2)

这一行:

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

应该是:

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

您正在分配指针(8个字节)而不是结构节点(24个字节)。在valgrind(www.valgrind.org)下执行你的程序很容易捕获到这样的问题。