#include<iostream>
#include<conio.h>

using namespace std;

struct node
{
    int info;
    node *left,*right;
};

int main()
{
    struct node *root;
    root=NULL;
    //root->info=NULL;
    //root = (struct node*)malloc(sizeof(struct node));
    if(root==NULL) //cout<<root->info;
    cout<<root->info<< " "<<root->left<<" "<<root->right<<"\n";
    getch();
    return 0;


}

why it is giving an error?

Dani AI

Generated

The crash happens because the program dereferences a NULL pointer. set root to NULL and then immediately accessed root->info (which triggers undefined behavior). is correct: do not read members from a pointer that is NULL.

Fix steps and safer patterns:

  • Make root point to a real node before accessing its members. In C++ allocate and initialize the node (or use a constructor/factory). In C allocate with malloc and initialize fields, and include <stdlib.h>. In modern C++ prefer nullptr instead of NULL, and prefer smart pointers (std::unique_ptr) or RAII to manage lifetime.
  • Initialize the left and right pointers inside the node so they do not contain garbage.
  • Always check a pointer for null before dereferencing if there is any doubt.

Minimal example of creating and using a node (C++ style):

node *root = new node;
root->info = 0;
root->left = root->right = nullptr;
std::cout << root->info << ' ' << root->left << ' ' << root->right << '\n';
delete root;

About the other replies: ’s suggestion about writing struct node *left; is not the real issue here — in C++ node *left; is fine because struct introduces the node type. The runtime error comes from dereferencing NULL, not the pointer-declaration syntax.

Quick debugging tips: compile with warnings enabled (-Wall -Wextra), run under a debugger (gdb) or memory tools (Valgrind or AddressSanitizer), and remove nonstandard constructs like conio.h/getch unless you need them for your platform.

Recommended Answers

All 3 Replies

are you sure you posted in the right forum, the code is in C++ yet this is the C forum and you forgot to post the error messages
Now in a glance, 1 error I see is you should initialize the following variables inside the structure as follows

struct node *left; 
struct node *right

oh yes..my mistake..this is C forum.sorry
it gives run time error.

Member Avatar for Member #907664

This is also incorrect:

> if(root==NULL) //cout<<root->info;
> cout<<root->info<< " "<<root->left<<" "<<root->right<<"\n";

You are trying to access the info member of root, which is NULL (due to your if statement); this will cause the program to crash.

It is best practice to always wrap statements in curly brackets to prevent unwanted behavior.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.