Segmentation Fault.

P

Prasad

I am executing this program but, getting error Segmentation Fault.

Can any one point out the error in this?

#include<iostream>

using namespace std;

typedef struct __Node
{
int data ;
struct __Node *left, *right ;
} NODE ;
NODE *ROOT = NULL ;

void Insert ( NODE *root, NODE *nNode )
{
if ( root )
{
//////////////
}
else
{
*root = nNode ;
}
}

void Insert ( int data )
{
NODE *tmp = new NODE ;
tmp -> left = tmp -> right = NULL ;
tmp -> data = data ;
Insert ( ROOT, tmp ) ;
}

int main ()
{
Insert ( 10 ) ;
cout << ROOT -> data << endl ;
return 0 ;
}

Thanks in advance.
Prasad
 
I

Ivan Vecerina

:I am executing this program but, getting error Segmentation Fault.
:
: Can any one point out the error in this?
:
: #include<iostream>
:
: using namespace std;
:
: typedef struct __Node

BTW: Identifiers starting by two unserscores (or an underscore and
an uppercase letter) are reserved for use by the implementation.
Don't use them, or your code will not be standards compliant.

: {
: int data ;
: struct __Node *left, *right ;
: } NODE ;
All-uppercase are typically used only for preprocessors definitions
(althouth it is not illegal to do otherwise).

: NODE *ROOT = NULL ;

You are never allocating this root node, therefore dereferencing
a null pointer.
Why not declare an actual variable instead of a pointer:
Node root;
Use &root when you need a pointer to the root.

Ivan
 
S

Sunil Varma

Prasad said:
I am executing this program but, getting error Segmentation Fault.

Can any one point out the error in this?

#include<iostream>

using namespace std;

typedef struct __Node
{
int data ;
struct __Node *left, *right ;
} NODE ;
NODE *ROOT = NULL ;

void Insert ( NODE *root, NODE *nNode )
{
if ( root )
{
//////////////
}
else
{
*root = nNode ;
}
}

void Insert ( int data )
{
NODE *tmp = new NODE ;
tmp -> left = tmp -> right = NULL ;
tmp -> data = data ;
Insert ( ROOT, tmp ) ;
}

int main ()
{
Insert ( 10 ) ;
cout << ROOT -> data << endl ;
return 0 ;
}

Thanks in advance.
Prasad

I dont which version of gcc you are using.
But g++ complains error on,
*root = nNode;

Here you are trying to fill object pointed to by root with nNode
pointer.
Probably what you wanted is

root = nNode.

Regards
Sunil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top