I'm observing segmentation fault
, when I try to allocate memory to a structure.
After memcpy()
I'm trying to copy the contents of one more structure to the above structure.
Below is the code snippet :
struct student {
char *username;
char *id;
int roll;
};
struct db {
struct student *s1;
struct student *s2;
};
void print_struct(struct student *);
int main (void) {
struct student *student1, *student2;
struct db *db1;
char *name = "ram";
char *id = "200ABCD";
int roll = 34;
student1 = (struct student *)malloc(sizeof(struct student));
student1->username = name;
student1->id = id;
student1->roll = roll;
printf("\nStudent 1\n");
print_struct(student1);
printf("\nStudent 2\n");
student2 =student1;
print_struct(student2);
printf("\nDb of s1\n");
db1->s1 = (struct student *)malloc(sizeof(struct student)); ===> segfault here
db1->s1 = student1;
print_struct(db1->s1);
return 0;
}
void print_struct(struct student *s) {
printf("Name: %s\n", s->username);
printf("Id: %s\n", s->id);
printf("R.No: %d\n", s->roll);
return;
}