-4

I'm having a hard time trying to understand what's wrong in my piece of code,

As you can see, it's a linked list and it's supposed to connect "Boxes", each Box has a int value and a pointer to the next Box, however I'm not being able to make it run and I don't know why.

Can anyone tell me why it's not running?

#include <stdio.h>
#include <stdlib.h>

struct node {
    int n;
    struct node *next;  
} node;

typedef struct node Box;

main()
{    
    Box *q, *r, *s;
    Box t;

    q = (Box *)malloc(sizeof(Box));
    r = (Box *)malloc(sizeof(Box));
    s = (Box *)malloc(sizeof(Box));

    q->n = 2;
    q->next->n = 3;
    r->n = 4;
    q->next->next = r;
    r->next = NULL;
    s->n = 5;
    s->next = NULL;
    t.n = 6;

    printf("================");
    printf("Q == %d\n", q->n);
    printf("R == %d\n", r->n);
    printf("S == %d\n", s->n);
    printf("{%d}{%d}{%d}{%d}{%d}", q->n, q->next->n, r->n, s->n, t.n);      
}
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
UendelC
  • 5
  • 3
  • Welcome to Stack Overflow! It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Paul R Jun 16 '16 at 12:29
  • 1
    You write `q->next->n` before you have made `q->next` point to anything – M.M Jun 16 '16 at 12:30
  • 2
    You need to provide a relevant title, also what you means by "it doesn't work" – blue112 Jun 16 '16 at 12:31

3 Answers3

3

Your initialization sequence is very confusing, which makes it invoke undefined behavior by writing through non-initialized pointers.

It should just be:

q->n = 2;
q->next = r;
r->n = 4;
r->next = s;
s->n = 5;
s->next = t;
t->n = 6;
t->next = NULL;

Also, please don't cast the return value of malloc() in C.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
3

You allocate memory for q

Box *q = malloc(sizeof(Box));

then you are using q->next without assigning it:

q->n = 2;
q->next->n = 3;
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
2

You are writing into non-allocated memory:

q->n = 2;
q->next->n = 3; //q->next points "into the wild" here

You probably intend something like this:

q = malloc(sizeof(Box));
q->next = malloc(sizeof(Box));
q->next->n = 3;

Since this is repetitive, you should write a routine to do this task:

void append(Box* where, int what) {
 ...
}

And for cleanup:

void delete(Box* where) {
 ...
}
choeger
  • 3,562
  • 20
  • 33