Reputation: 141
#include <stdio.h>
#include <stdlib.h>
struct Person {
char* name;
int age;
};
void printit(struct Person *person) {
printf("%s %d \n",person->name,person->age);
}
int main(int argc, char** argv) {
struct Person *p = malloc(sizeof(struct Person));
printf("Enter name: ");
scanf("%s", p->name);
printf("Enter age: ");
scanf("%d", &(p->age));
printit(p);
free(p);
}
Enter name: asdf
Segmentation fault: 11
I don't know why it is giving segmentation fault....
Upvotes: 0
Views: 174
Reputation: 12272
You allocated memory for the struct
.
But you did not allocate memory where p->name
would point to
Add this to your code.
struct Person *p = malloc(sizeof(struct Person));
p->name = malloc(100);
No type should be explicitly allocated space inside a struct.
When you did
struct Person *p = malloc(sizeof(struct Person));
space gets allocated for name
and age
both. But notice that name
is a pointer variable. Space has been allocated for the pointer variable, but not where the pointer will point to.
It is like when you do
char* p;
The variable p
is created, space is allocated for it, but if you want to use it, you have two options.
1) Either make it point to some existing allocated memory
char* p;
char arr[10];
p = arr;
2) Or allocate memory where it will point at.
char* p = malloc(sizeof(char));
Upvotes: 5