-2
#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.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
ljs0626jh
  • 3
  • 2
  • 4
    `struct queue *q;`. That is a NULL pointer. Which of course can cause a seg fault if dereferenced. Why did you comment out the `malloc`? Similar problem for `d` which is an uninitialized pointer. – kaylum Apr 18 '22 at 05:40
  • I replaced struct queue *q = (queue*)malloc(sizeof(struct queue)); instead of struct queue *q. However, it still generated segmentation fault. So, am I need to malloc both queue and data? – ljs0626jh Apr 18 '22 at 05:45
  • `struct data *d;` sufferers from the same problem. It is an *Uninitialized Pointer* pointing to some random address in memory. Attempting to access or write to that random location guarantees a segfault. A few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) (ignore the titles, the answers discuss pointer basics) – David C. Rankin Apr 18 '22 at 05:48

2 Answers2

1

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;
Evgeniy
  • 11
  • 1
  • Instead of `struct data *d = (struct data *)malloc(sizeof(struct data));` you can write: `struct data *d = malloc(sizeof *d);` - there's no need to cast and it's often clearer to take the `sizeof` the dereferenced pointer than repeating the type. – Ted Lyngmo Apr 18 '22 at 09:05
1

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.

assafp
  • 69
  • 5