Reputation: 31
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?
Upvotes: 2
Views: 188
Reputation: 753475
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.
Upvotes: 0
Reputation: 14895
This line:
dizi[k].next->sonra = malloc(sizeof(struct ekstra));
is dereferencing
dizi[k].next
and I suspect that has a junk value.
Upvotes: 3