0

I have these two structures :

struct member {
  char *nickname;
  char *group;
};

struct node {
   struct member mbr;
   struct node   *next;
};

Further in my code I do this :

struct node* n = (struct node*)malloc(sizeof(struct node));

And get a "Segmentation fault" error at this line when I run the program :

strcopy(n->mbr.nickname, temp->nickname);

I've been trying for a while to solve this problem and I've searched on the web, but I didn't find any solution yet. I'm guessing the structure inside 'n' isn't initialized. I did a few test that looked like :

n->mbr = (struct member*)malloc(sizeof(struct member));

But then I get another error : "incompatible types when assigning to type 'struct member' from type 'struct member *'"...

Can anyone tell me what I'm doing wrong? Thanks.

1
  • 1
    Is strcopy() a typo or your own function? Commented Oct 20, 2013 at 23:05

1 Answer 1

2

You don’t need to allocate mbr; you need to allocate mbr.nickname.

struct node* n = malloc(sizeof (struct node));
n->mbr.nickname = malloc(some number of characters);

Then use strncpy. Alternatively,

n->mbr.nickname = strdup(temp->nickname);

which is the same as doing that, but using strlen(temp->nickname) + 1 as the size.

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

5 Comments

Hm, strncpy is not such a good idea when the length of the string is known, anyhow. Better use memcpy, then.
@JensGustedt: Is the length of the string known? If the idea is to find it using temp->nickname, I’ve added strdup.
Might be worth mentioning that strdup is POSIX and not standard C.
OP tagged C, not posix - stick with strlen(x) (no strndup or strdup)
It worked! Thank you so much, it's been a while since the last time I did some C programming and I think I'm not quite back into it ;)

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.