简体   繁体   中英

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

I have a struct TREE defined this way:

typedef struct TREE {
    NODE *head;
} TREE;

and a struct NODE defined as:

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

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?

Till,

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 *treeptr->head);

before doing

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM