I’m trying to learn C, and now I’m playing with structures.
I have the following piece of code:
#include <string.h>
struct user {
unsigned int utime;
char *username;
};
void main()
{
char username[] = "root";
struct user *u;
strcpy(u->username, username);
}
But, when I try to run it, it generates a Segmentation fault.
What’s wrong with it?
uis a pointer to a struct but you didn’t allocate any memory for it yet. The line must bestruct user *u = malloc(sizeof(struct user)). Additionally you will also have to allocate memory for theusernamepointer within your struct before callingstrcpy.