Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nested list struct c++

I have a nested list:

struct CHANNEL {
char channel_id[200];
char name_Channel[200];
};

struct Line {
CHANNEL* chan;
PROGRAM* prog;
HOST* host;
DATE_TIME* date;
struct Line* next;
};

but when I create a Line variable and try to work with it

    char number[200];
    Line* p;
    p = (struct Line*)malloc(sizeof(*p));

    strcpy_s(p->chan->channel_id, number);

Visual studio says: "Dereferencing NULL pointer ‘p’" and "Access violation reading location 0xFFFFFFFFFFFFFFFF." in string.h

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can it be fixed?

>Solution :

This line:

p = (struct Line*)malloc(sizeof(*p));

Allocates memory for an object of struct Line.

It does not initialize the object.
One of the uninitialized data members of this object is CHANNEL* chan.
Therefore when you try to access p->chan->channel_id, p->chan is uninitialized and you cannot use it to access the CHANNEL struct members.

You can solve this specific issue by "manually" initializing the members of p after the allocation.

But if you are using c++ (as suggested by the tags you put on your question), it’s better to use new which calls the object’s constructor after performing the memory allocation. For this to work, you will need to add a constructor to struct Line that will initialize all the members (and specifically initialize the pointers like CHANNEL* chan to point to some valid CHANNEL object). Also in c++ it’s usually prefered to use smart pointers over raw ones.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading