Can you help me understand why this code randomly results in memory access violation? Goal is to generate a binary search tree from sorted list.
Stepping through code I noticed a behavior where node
pointer randomly changes when a recursive calls to fromSortedArray()
function is returned. To give you a contex I am compiling this app using XCODE.
#include <iostream>
using namespace std;
class BST{
private:
struct Node {
int val;
struct Node *left, *right;
} *root;
public:
BST(){
this->root = NULL;
}
struct Node * fromSortedArray(int data[], int left, int right){
if(left>right) return NULL;
int m = left+(right -left)/2;
struct Node *node = (struct Node *) malloc(sizeof(struct Node*));
node->val = data[m];
node->left = this->fromSortedArray(data, left, m-1);
node->right = this->fromSortedArray(data, m+1, right);
return node;
}
void fromSortedArray(int data[], int n){
this->root = fromSortedArray(data, 0, n-1);
}
void deleteTree(struct Node *root){
if(root==NULL) return;
deleteTree(root->left);
deleteTree(root->right);
delete root;
}
void deleteTree(){
this->deleteTree(this->root);
}
void traverse(struct Node *root){
if(root == NULL) return;
if(root->left!=NULL)traverse(root->left);
printf("%d ", root->val);
if(root->right!=NULL)traverse(root->right);
}
void traverse(){
this->traverse(this->root);
}
~BST(){
deleteTree();
}
};
int main(int argc, char * argv[]){
BST tree;
int data[] = {2,3,5,6,7,9};
tree.fromSortedArray(data, 6);
tree.traverse();
cout << "\n";
return 0;
}