Right now I'm dumbfounded as to why the following program appears to work fine on my CentOS 6 box, but running the compiled program results in a Seg Fault 11 on my Mac OSX. I debug on my Macbook using Eclipse and the gdb debugger with some strange results. It's a simple binary tree example:
#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;
}
And the header file:
/*
* 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_ */
Any tips appreciated, thanks!
This line:
struct node *n = (struct node*)malloc(sizeof(struct node*));
Should be:
struct node *n = (struct node*)malloc(sizeof(struct node));
You are allocating a pointer (8 bytes) rather than a struct node (24 bytes). Problems like this are easy to catch by executing your program under valgrind (www.valgrind.org).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.