c - signal SIGABRT on return 0 -


everything seems run fine except when program attempts return 0 when error:

thread_1: signal sigabrt 

i'm not sure i'm doing wrong think may how i'm using pointers (passing array of doubles reference). believe has when memory freed, i'm bit new it's hard figure out. thanks!

edit: readgrades() reading 4 integers text file input.txt , adding them array passed in

#include <stdio.h> #include <stdlib.h> #include <math.h>  /*  * readgrades()  * input:  double array of grades (double grades[])  * output: number of grades read (int numofgradesread)  */ int readgrades(double (*grades)[]) {  int numofgradesread = 0,     count = 0,     numread;  char buf[1000]; file *file = fopen("input.txt", "r");  if (file == null) {     perror("can't open file"); } else {     while (fgets(buf, sizeof(buf), file)) {          // convert buf integer         numread = atoi(buf);          // add number read grades[]         if (numread != -999) {             (*grades)[count] = numread;             numofgradesread++;             count++;         }     } }  fclose(file);  return numofgradesread; }  void frequency(double grades[], int numofgrades) {  }  int main() {  double grades[100]; int i;  // initialize grades values 0 (i = 0; < sizeof(grades)/sizeof(int); i++) {     grades[i] = 0; }  int numofgradesread = readgrades(&grades);  (i = 0; < 4; i++) {     printf("%f", grades[i]); }  return 0; } 

a major error line:

for (i = 0; < sizeof(grades)/sizeof(int); i++) { 

as result of error, setting value of elements of grades using out of bound indices, leads undefined behavior.

it should be

for (i = 0; < sizeof(grades)/sizeof(double); i++) {                                    // ^^^^^^^ needs double not int 

you can use convention

for (i = 0; < sizeof(grades)/sizeof(grades[0]); i++) { 

to make code more robust.

also, instead of using hard coded number 4 in for loop print grades, want use numofgradesread. in addition, print space or newline between grades make output easier read.

for (i = 0; < numofgradesread; i++) {     printf("%f\n", grades[i]); } 

Comments