#include <stdio.h>
#define x 10
struct data
{
int num;
int state;
};
struct queue
{
struct data *q1[x];
int num;
};
struct queue *q;
void insert(struct queue *q, struct data *d)
{
d->state = 0;
q->q1[0] = d;
q->num = 1;
}
int main()
{
struct data *d;
// struct queue *q = (queue*)malloc(sizeof(struct queue));
insert(q, d);
printf("%d\n %d\n", q->q1[0]->state, q->num);
}
I wrote the code like this. And it caused segmentation fault (core dumped). I wonder why it is happened and how should I edit it.
Thank you.
CodePudding user response:
q and d are pointers. You can't access structure members, because No memory has been allocated for this structure.
#include <stdlib.h>
<...>
struct data *d = (struct data *)malloc(sizeof(struct data));
struct queue *q = (struct queue *)malloc(sizeof(struct queue));
<...>
free(d);
d = NULL;
free(q);
q = NULL;
CodePudding user response:
You should make sure that all the pointers you use are initialized. defining a pointer d, without pointing it to a valid structure, and then trying to use the memory that it points to, will probably generate a segmentation fault.