c - Runtime error, input string in array -


this input strings , code supposed read file. when compile using lastest dev c++ @ home, runs perfectly. dev c++ @ school crashes program (and after debug know is) @ = 9. line michael nguyen 71 70 91 93 28.

i fixed changing char studentfirst[15] char studentfirst[17]. name supposed put in michael , nguyen aren't more 14 char each. me take @ it. did understand wrong line fscanf(infile, "%s%s", studentfirst, studentlast)?

input:

sidra amartey 90 88 70 74 70 rebecca brown 85 98 73 78 74 leslie carter 92 73 86 36 87 ashley guillen 95 26 90 83 85 ryan hilliard 75 66 69 100 52 dawn hopkins 84 69 66 88 74 kyle jiwani 7 99 96 84 89 melvin johnson 73 80 63 38 88 edward maun 82 85 72 75 99 angelo morrison 95 97 80 31 70 michael nguyen 71 70 91 93 28 zack nutt 82 85 97 74 98 diana patel 77 70 88 68 82 patrick perez 87 77 21 88 7 abigail peterson 64 81 75 85 70 jennifer putnam 39 91 85 80 70 kimberly sanjel 64 69 74 97 12 marisa santos 63 77 90 15 60 hannah shrestha 13 77 95 97 99 linda stoll 50 85 72 91 23 victoria taylor 95 93 74 63 90 haily wright 80 90 99 68 84 

code:

int loadstudentnamesgrades(studentnode students[], const char * filename) {     file * infile;     char studentfirst[15] = {0};     char studentlast[15] = {0};     int numstudents = 0;     int = 0, j = 0;     if((infile = fopen(filename, "r")) == null)     {         printf("cannot access file %s\n", filename);         system("pause");         exit(1);     }     for(i = 0; < max_students && (fscanf(infile, "%s%s", studentfirst, studentlast) == 2); i++, numstudents++)     {         for(j = 0; j < max_grades; j++)         {             fscanf(infile, "%d", &students[i].grades[j]);         }         students[i].name = (char*)malloc(strlen(studentfirst) + strlen(studentlast) + 2);         strcpy(students[i].name, strcat(strcat(studentfirst, " "), studentlast));     }      return numstudents; } 

your problem undefined behavior. first forget count terminating \0, michael nguyen 15 chars, not 14. crash result of previous line there angelo morrison 16 long, more studentfirst can hold! , abigail peterson 17 long, studentfirst needs 17 long. studentlast needs 9, not problem.
not appear have understood fscanf wrong. might not understand strcat uses studentfirst hold full name.


Comments