views:

148

answers:

3

Hi,

I have two structure in c

struct data{
  char *name;
};

struct lst{
   struct lst *next;
   struct table *data;
};

when I'm trying to assign a name like

l->data->name = d->name; printf("%s",l->data->name);

it gives segmentation fault. So is it because read-only memory or caused by another reason ?

ok I solved the problem : ) I've done :

l->data = d; d has the name already :) thanks all

+5  A: 

Just before you do that segmentation-violation-causing instruction, insert:

printf( "%p\n", l);
printf( "%p\n", l->data);
printf( "%p\n", d);
printf( "%p\n", d->name);

and see which one is set to NULL (or an invalid value).

Your segmentation violation is almost certainly caused by an uninitialized pointer.

paxdiablo
+1, You forget to print also d :)
Patrick
Or just use a debugger :) `printf()` debugging.. Are we in the 70s? :D
Andreas Bonini
@Andreas - Why kill a cockroach with a rocket launcher?
Chris Lutz
Because a debugger is an invaluable tool and should be learned as soon as possible.
Andreas Bonini
@Andreus, debuggers are not always an option. They're easy to fire up within an IDE but having to recompile in debug mode and load up into an external debugging tool is sometimes slower than just recompiling with a couple of extra printf statements.
paxdiablo
Thanks, @Patrick, missed that one.
paxdiablo
@paxdiablo, sure, sometimes it is slower to do that, but sometimes it's also nice to be able to see that the pointer is null, allocate the memory, and continue debugging so you can see if there are any other problems later on so you won't have to continue to keep recompiling with additional prints. It may not be the case in OP's situation, but sometimes it's very difficult to get to the code you're fixing and it's simply easier to not have to worry about having to restart your application just so you can try to print out a few more values.
mrduclaw
A: 

I can be caused by a member pointing into an invalid zone.

Patrick
A: 

l->data is most likely NULL

knittl