Reputation: 277
I'm a beginner in C programming. I've trouble using the printf function. When I run the following program I'm getting A segmentation fault. Please tell me what I'm doing wrong. What does a segmentation fault actually mean?
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
char *name;
int rollnum;
int marks;
}
student_data;
int main()
{
student_data stud1;
student_data *ptr;
ptr = (student_data *)malloc(sizeof(student_data));
printf("\n NAME OF THE STUDENT: " );
scanf("%s", &ptr -> name);
printf("\n ROLL NUMBER OF THE STUDENT: " );
scanf("%d", &ptr -> rollnum);
printf("\n MARKS OF THE STUDENT: " );
scanf("%d", &ptr -> marks);
printf("\nPRINTING ROLL NUMBER %d", ptr -> rollnum);
printf("\nPRINTING MARKS %d", ptr -> marks);
printf("\nPRINTING NAME %s", ptr -> name);
}
-:output:-
NAME OF THE STUDENT: ajish
ROLL NUMBER OF THE STUDENT: 2
MARKS OF THE STUDENT: 60
PRINTING ROLL NUMBER 2 PRINTING MARKS 60 Segmentation fault
Upvotes: 0
Views: 464
Reputation: 70369
You are not initializing ptr -> name
which leads to undefined behaviour in the rest of the code using ptr->name
.
add ptr->name = (char*) malloc(1000); memset (ptr->name, 0x00, 1000);
after malloc
and before the first printf
.
General remark:
You need to always initialize pointers. When working with scanf
you need to be aware that you must allocate/provide enough space to hold whatever might be entered/read (as stated in the documentation) otherwise you get problems with memory management and security and data integrity (like buffer overflows etc.).
Upvotes: 0
Reputation: 21419
You forgot to allocate some memory to student_data.name
.
As per the scanf
documentation, ptr->name
should point to an already allocated memory buffer.
Upvotes: 3