Nick Nick - 2 months ago 12x
C Question

Segmentation fault with char array member of struct using strcpy()

I have a struct TREE that looks like this:

typedef struct TREE {
NODE *head;

and a struct NODE that looks like this:

typedef struct NODE {
char boss[30];
char name[30];
struct NODE *firstChild;
struct NODE *secondChild;
struct NODE *thirdChild;
struct NODE *fourthChild;

In my main, I have:

TREE companyStructure;
TREE *treeptr;
treeptr = &companyStructure;
strcpy(treeptr->head->name, "Ben");

But this gives me a segmentation fault. Can someone help me explain why this is the case? Is there some memory management that I'm not doing that I need to be doing?



treeptr = &companyStructure;

Things look good. But then considering the fact that you have

NODE *head;

you need to allocate memory for head. So most likely you've missed

treeptr->head=malloc(sizeof *head);

before doing

strcpy(treeptr->head->name, "Ben");

Also, check [ this ] on why should you use strncpy instead of strcpy.