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
How can it be fixed?
CodePudding user response:
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.