我在观察segmentation fault
,当我尝试分配内存的结构。Segfault虽然malloc在C结构
memcpy()
之后我试图将一个更多结构的内容复制到上述结构中。
下面是代码片断:
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;
}
[请参阅此讨论关于为什么不在'C'中输入'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –
什么是memcpy?哪里? – Lundin