2

I have problem with linked lists. I have two structures:

struct ekstra
{
    char isim[256];
    int deger;
    struct ekstra *sonra;
};

struct node
{
    char name[256];
    int val;
    struct ekstra *next;    
};

and I have these:

struct ekstra *tmp;
struct node dizi[12];

Somewhere in my code there is

tmp = dizi[k].next;
tmp=tmp->sonra;

and if I do this:

tmp = malloc(sizeof(struct ekstra));

there is no problem.

But if I do this:

dizi[k].next->sonra = malloc(sizeof(struct ekstra));

I get a SegFault. Why is this happening?

12
  • 1
    You're best off running the code with the help of a debugger. On linux, valgrind is great for pointing out segmentation faults. Also, on Windows, the visual studio debugger is quite useful. Commented Jun 7, 2012 at 23:25
  • 4
    Maybe you misuse array index k. Please post full code Commented Jun 7, 2012 at 23:26
  • 4
    @GeorgeGaál Please don't ask for the full code, but more complete code that can reproduce the problem. Commented Jun 7, 2012 at 23:28
  • @Drise That is to say "the least amount of complete code that can reproduce the problem." I agree with George that you need to ensure that k is within the bounds of the array and also ensure that next is not null? The GNU Debugger would also be useful for troubleshooting this. Commented Jun 7, 2012 at 23:33
  • 1
    k is 0 here there is no problem with k Commented Jun 7, 2012 at 23:34

2 Answers 2

3

This line:

dizi[k].next->sonra = malloc(sizeof(struct ekstra));

is dereferencing

dizi[k].next

and I suspect that has a junk value.

Sign up to request clarification or add additional context in comments.

Comments

0

These two lines:

tmp = dizi[k].next;
tmp = tmp->sonra;

probably copy an invalid pointer into tmp. When you assign to tmp with malloc(), the valid pointer from malloc() overwrites the invalid value already in tmp.

When you use:

dizi[k].next->sonra = malloc(sizeof(struct ekstra));

you are referencing the invalid pointer (to evaluate the address where the sonra member is stored), and that is causing the segmentation fault.

If you wrote:

*tmp = 0;

you would probably get a segmentation fault too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.