[Solved] Program crashes when a function returns empty


The main problem I see with your code is the reading loop, it has mainly two issues

  1. Read: Why is while (!feof(rPtr)) always wrong.

  2. You must check the return value of scanf(), and prevent scanf()‘s from overflowing the destination buffer, so the loop condition should be

    while (fscanf(rPtr, "%14s%lf%lf%lf", fromDb.name, &fromDb.dArea, 
               &fromDb.dLength, &fromDb.dFormFactor) == 4)
    

How about this

int
myReadFile(struct database *db, double area, double length, double formFactor)
{
    FILE *rPtr;
    if ((rPtr = fopen("objects.dat", "r")) == NULL)
        printf("Couldn't open the file to read.\n");
    else
    {
        while (fscanf(rPtr, "%14s%lf%lf%lf", db->name, &db->dArea, 
            &db->dLength, &db->dFormFactor) == 4)
        {
            if ((db->dArea != area) || (db->dLength != length) || 
                (db->dFormFactor != formFactor))
            {
                continue;
            }
            fclose(rPtr);
            return 0;
        }
    }
    fclose(rPtr);
    return -1;
}

And in the main function

struct database result;
if (getValues(&result, myObjectList[i].oArea, 
    myObjectList[i].oLength, myObjectList[i].oFormFactor) == 0)
{
    fprintf(stderr, "%s\n", result.name);
}

2

solved Program crashes when a function returns empty