Reputation: 87
I have the following code and I am trying to assign a value to the structure name but it is returning me segment core error. Why is that?
struct group {
char *name;
struct user *users;
struct xct *xcts;
struct group *next;
};
int add_group(Group **group_list_ptr, const char *group_name) {
Group *newGroup = malloc(sizeof(Group));
strcpy(newGroup->name, group_name);
}
Upvotes: 1
Views: 44
Reputation: 726929
You have malloc
-ed the struct
, but you did not malloc
the string. The pointer inside the struct
is uninitialized, so you cannot strcpy
anything into it yet.
You have to allocate memory for your string, assign that memory to name
, and only then do strcpy
:
Group *newGroup = malloc(sizeof(Group));
newGroup->name = malloc(strlen(group_name)+1); // +1 for '\0' terminator
strcpy(newGroup->name, group_name);
Upvotes: 2