Reputation: 2008
I am using eclipse for C++ program.
After building my code when I am running the code I am getting name.exe has stopped working error. Same code is working fine here http://codepad.org/2c5xFbLM .
Please help me finding this issue.
Thanks in advance.
My code :
#include<iostream>
#include<math.h>
#include <cstdlib>
using namespace std;
struct node{
struct node * lc;
struct node * rc;
int data;
};
typedef struct node Node;
Node * getNewNode(int data){
Node * node = NULL;
node = (Node*)malloc(sizeof(node));
node -> data = data;
node -> lc = NULL;
node -> rc = NULL;
return node;
}
Node * buildBst(Node * root,int data){
if(NULL == root){
return getNewNode(data);
}
if(data > root -> data){
root -> rc = buildBst(root->rc,data);
}else{
root -> lc = buildBst(root->lc,data);
}
return root;
}
void printInorder(Node * root){
if(root != NULL){
printInorder(root -> lc);
cout << root -> data << " ";
printInorder(root -> rc);
}
}
int main(int argc, char* argv[]) {
int arr [] = {2,3,4,1,5,9,0,3};
Node * root = NULL;
for(int i = 0;i < 6; ++i){
root = buildBst(root,arr[i]);
}
printInorder(root);
cout << endl;
}
Upvotes: 1
Views: 376
Reputation: 503
Since you're using C++, use the new
operator instead of malloc
, the crash happened upon the 14th iteration at your call to malloc, or your 4th node creation, because of the additional padding with debugging, it allowed it in debug mode ( though technically UB otherwise ) and probably wrote through the guard bytes.
Likewise, it crashed on the malloc code because you were using sizeof(node)
vs sizeof(Node)
.
Upvotes: 4