0

**I have traced through the code 3 times but I still cant figure out the cause of the seg fault, I am trying to get a menu printed by opening files and displaying the contents in organized form, it so frustrating, I am already confused by my code and even more so by seg fault, any help would be highly appreciated, I know this will turn into a code review ​

typedef struct{
   char item[30];
   char quantity[20];
   int calories;
   float protein;
   float carbs;
   float fats;
} food;


typedef struct {
   char month[4];
   int day, year;
} date;


int foodCount;   // counter variable to keep track of the number of foods that are chosen


  void initializeArray(FILE *dataFile, int arraySize, food foodType[]) // arrayProcessing.c
{
   int i;

// struct food foodType[arraySize];

   for(i=0;i<arraySize;i++)
   {
      scanf("%s",foodType[i].item);
      scanf("%s",foodType[i].quantity);
      scanf("%d",&foodType[i].calories);
      scanf("%f",&foodType[i].protein);
      scanf("%f",&foodType[i].carbs);
      scanf("%f",&foodType[i].fats);
   }
}
// used for the food arrays as well as the chosen foods
void printArray(int arraySize, food foodType[])                      // arrayProcessing.c
{
   int n;
   printf("FOOD ITEM%25s%9s%10s%8s%8s\n","QUANTITY","CALS","PRO","CARBS","FAT");

   for(n=0;n<arraySize;n++){
      printf("%d. %-20s\t%10s\t%3d\t%5.2f\t%5.2f\t%5.2f\n",n+1,foodType[n].item,foodType[n].quantity,
      foodType[n].calories, foodType[n].protein, foodType[n].carbs, foodType[n].fats);
   }
}

int printMainMenu()                                                  // menu.c
{
int choice;

    printf("\n MAIN MENU");
    printf("\n 1. choose lean protein");
    printf("\n 2. choose fruit");
    printf("\n 3. choose complex carbs (starches & grains)");
    printf("\n 4. choose fibrous carbs (veggies & greens)");
    printf("\n 5. choose dairy");
    printf("\n 6. choose fats, oils, nuts, seeds");
    printf("\n 7. show totals");
    printf("\n 8. quit program");
    scanf("%d", &choice);

    return choice;
int main (){
   int arraySize, choice;
   FILE *dataFile;
   food foodType[arraySize];

   do
   {

      choice=printMainMenu();
      switch(choice)
      {
         case 1: {
            dataFile=fopen("leanProteins.txt","r");
            fscanf(dataFile,"%d",&arraySize);
            initializeArray(dataFile, arraySize, foodType);
            printArray(arraySize, foodType);
      break;
      }
         case 2:{
            dataFile=fopen("fruit.txt","r");
            fscanf(dataFile,"%d",&arraySize);
            initializeArray(dataFile,arraySize, foodType);
            printArray(arraySize, foodType);
            break;
         }
         case 3:{
            dataFile=fopen("complexCarbs.txt","r");
            fscanf(dataFile,"%d",&arraySize);
            initializeArray(dataFile,arraySize,foodType);
            printArray(arraySize, foodType);
            break;
         }

         case 4:{
            dataFile=fopen("fibrousCarbs.txt","r");
            fscanf(dataFile,"%d",&arraySize);
            initializeArray(dataFile,arraySize,foodType);
            printArray(arraySize, foodType);
            break;
         }
         case 5:{
            dataFile=fopen("dairy.txt","r");
            fscanf(dataFile,"%d",&arraySize);
            initializeArray(dataFile, arraySize, foodType);
            printArray(arraySize,foodType);
            break;
         }
         case 6:{
            dataFile=fopen("fats.txt","r");
            fscanf(dataFile,"%d",&arraySize);
            initializeArray(dataFile, arraySize, foodType);
            printArray(arraySize,foodType);
            break;
         }
         case 7:{
            printf("show totals");
            break;
         }
         case 8:{
            exit(0);
         }
         default:
         printf("invalid selection!");
      }
   }while(choice!=8);
   return 0;
}
static_sid
  • 23
  • 1
  • 3

1 Answers1

2

Hint only since this is almost certainly classwork, and you'll become a much better developer if you learn to nut things out yourself :-)

int arraySize, choice;
FILE *dataFile;
food foodType[arraySize];

Here's a question you should ask with regard to the snippet above. What is the value of arraySize at the point where the foodType array is created?


A couple of other things to consider.

  1. You're likely going to run out of file handles if you keep opening files and not closing them.
  2. You appear to want to read food details from a file (which you open) but you never actually use the file handle. Instead, you scanf the information from standard input.
  3. And, on that scanf (specifically with "%s"), you need to be absolutely certain that your data is correct. Crashing is frequently caused by reading in a string that's too long for the buffer you've provided.
  4. Still with the scanf("%s"), you should be aware that it will stop on the first whitspace so, if your file contains the "Long grain Basmati" complex carb, all you're going to see is Long. And this will almost certainly complicate your input as you try to read the rest of the line as non-string data (like a calorie count of "rice", for example).
  5. You should generally always check the return value of the scanf family to ensure it has scanned the number of items you expected.

Those last three points could probably be solved with a more robust input function, one which prevents buffer overflow and checks the data being read to ensure it's valid (like reading as a string first, checking the content as a string, then converting to integer or float).

I have such a beast here that works well for standard input, it reads the entire line safely. It wouldn't be hard to adapt this to use any file handle and then you could use sscanf to turn that into individual fields after checking.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • I tired it but it still gives a seg fault, I tried assigning arraysize to a variable as well as to a value but it wont work – static_sid Nov 24 '19 at 17:54
  • @static_sid Your program likely has many bugs. You should accept this answer, and ask a separate question with corrected source. Or just learn how to debug small programs https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Employed Russian Nov 24 '19 at 20:26