c - Why am I getting a Segmentation Fault in function search_lastname? -
the following program accepts data user of student name , last name , score. function search_lastname supposed search records of given last name. gives segmentation fault. other function print records , cases switch have been created further functions yet added program .
#include<stdio.h> #include<string.h> #include<stdlib.h> char **first_name, **last_name; float *score; int entry; void print(); void search_lastname(char search_last_name[21]); int main() { int i,option; char search_last_name[21]; { printf("\nplease indicate number of records want enter (the minimum number of entries 5) :"); scanf("%d",&entry); } while(entry<=4); score=(float*)malloc(entry*sizeof(float)); first_name=(char**)malloc(entry*sizeof(char*)); last_name=(char**)malloc(entry*sizeof(char*)); for(i=0;i<entry;i++) { first_name[i]=(char*)malloc(21*sizeof(char)); last_name[i]=(char*)malloc(21*sizeof(char)); } printf("please input records of students (enter new line after each record), following format first name last name score \n"); for(i=0;i<entry;i++) { scanf("%s%s%f",&first_name[i],&last_name[i],&score[i]); /*input of records itself*/ } { printf("\nplease choose appropriate options :"); /*switch statement choosing options.*/ printf("\nprint records (press 1)\nadd new record (press 2)\ndelete records (press 3)\nsearch last name (press 4)\nsort score (press 5)\nsort last name (press 6)\nfind median score (press 7)\nexit program (press 0)"); scanf("%d",&option); switch(option) { case 1 :print(); break; case 2 : break; case 3 : break; case 4 : printf("\n please enter last name want search: "); scanf("%s",search_last_name); search_lastname(search_last_name); break; case 5 : break; case 6 : break; case 7 : break; case 0 : break; default : printf("\n please enter valid option."); } } while(option>=1 && option<=7); return 0; } void print() { int i; printf("\n records of students follows :"); for(i=0;i<entry;i++) { printf("\nfirst name:%s, last name:%s, score:%f\n",&first_name[i],&last_name[i],score[i]); } } void search_lastname(char search_last_name[21]) /*funtion search last name*/ { int i,counter=0; for(i=0;i<entry;i++) { if(strcmp(search_last_name,last_name[i])==0) { printf("\nfirst name:%s, last name:%s, score:%f\n",first_name[i],last_name[i],score[i]); } } }
your problem usage of scanf() function. need change
scanf("%s%s%f",&first_name[i],&last_name[i],&score[i]); to
scanf("%20s %20s %f", first_name[i], last_name[i], &score[i]); without length modifier, %s specifier won't able seperate input strings , over-writing memory area past allocated memory, causing undefined behavior.
also, it's recommended check return value of scanf() ensure proper input.
note:
- the recommended signature of
main()int main(void). - do not cast return value of
malloc(), family.
Comments
Post a Comment