Thread: program crashes on closure.

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    255

    program crashes on closure.

    ok the HW assignment i was working on i got it back and it crashed on closure. guess why cause i had put the cin.get() at the end and always just exited by clicking x so it just never occured to me it wasnt working. so of course the teacher hit enter and it died trying to close.

    so i have no idea why a program would execute just fine and THEN die trying to close. the little bits of commented out code here and there was me trying to fix the problem where it reads the first bit of data in the file then skips over the second one so thats why.

    but mainly why does it die closing?

    (yes i know this is my whole assignment but eh not sure what part is killing it)


    Code:
    /********************************************************************************
     * FILENAME			:school_1.cpp												*
     * PROGRAMMER		:DELETED FOR SECURITY REASONS												*
     * PURPOSE			:Determine whether file is readable and if so read it and   *
     *					:perform certain calculations with numbers					*
     *******************************************************************************/ 
    #include <fstream>
    #include <string>
    #include <iostream>
    using namespace std;
    
    
    //function prototypes
    
    double calc_average(int count,int file_data[]);
    int smallest_number(int file_data[],int count);
    int load_array(ifstream& in, int file_data[], int arraysize);
    int count_abv_avg(int file_data[],int count,double avg);
    void display(double avg,int count_abv);
    void print_array(int file_data[],int count);
    
    int main()
    {
    	//variable intialization
    	bool exit = false;
        double avg;
    	int smallest;
    	int count_abv = 0;
    	int count = 0;
    	const int arraysize = 99;
    	int file_data[arraysize];
    	ifstream in("onehundred.dat"); // OPEN FILE HERE
    	
    	//main program control loop
    	while(exit == false)
    	{
    	if(in.is_open())
    	{
    	count = load_array(in, file_data, arraysize);
    	
    	if(count == -1)
    		exit = true;
    	else
    	{
        print_array(file_data,count);
    	avg = calc_average(count,file_data);
    	count_abv = count_abv_avg(file_data,count,avg);
    	smallest = smallest_number(file_data,count);
    	display(avg, count_abv);
    	exit = true;
    	}
    	}
    	else
    	{
    		cout << "Your file does not exist please exit and try again.\n";
    		exit = true;
    	}
    	}
    	//cout << "\nPRESS ANY KEY TO CONTINUE\n";
    	//cin.get();
    	in.close();
    	return 0;
    }//it says it DIES HERE
    
    
    
    /********************************************************************************
     * PURPOSE			:Display all neccessary outputs								*
     * PASSED IN		:avg, count_abv												*
     * RETURNED			:Nothing												    *
     *******************************************************************************/ 
    void display(double avg,int count_abv)
    {
    	cout << "\nThe average of the array:\t" << avg
    		<< "\nThe number of numbers above the average:\t" << count_abv << endl;
    }
    
    /********************************************************************************
     * PURPOSE			:Display all data found in file												*
     * PASSED IN		:file_data[], count											*
     * RETURNED			:Nothing												    *
     *******************************************************************************/ 
    
    
    void print_array(int file_data[],int count)
    {
    	cout << "The data in this File\n" << file_data[0] << "VALUE OF COUNT" << count<<endl;
    	for(int i = 0;i < count;i++)
    		cout << file_data[i] << "Value if I:" << i << endl;
    }
    
    /********************************************************************************
     * PURPOSE			:Calculate average of data found in file												*
     * PASSED IN		:count,file_data[]											*
     * RETURNED			:average												    *
     *******************************************************************************/ 
    
    
    double calc_average(int count,int file_data[])
    {
    	int total = 0;
    	double average = 0;
    	int i;
    	for(i = 0;i < count;i++)
    		total += file_data[i];
    	average = total/i;
    	return average;
    }
    
    /********************************************************************************
     * PURPOSE			:Reads the file data into array and determines              *
     *					:the number of elements in array							*
     * PASSED IN		:&in,file_data[],arraysize									*
     * RETURNED			:i											    *
     *******************************************************************************/ 
    
    int load_array(ifstream& in, int file_data[], int arraysize)
    {
        int elementsize = 0;
    	//in >> file_data[0];
    	//cout << file_data[0];
    	
    	
    	
    		if(!(in >> file_data[elementsize]))
    		{
    			cout << "File is Empty\n";
    			elementsize = -1;
    		}  
    		elementsize++;
            //cout << "0 ELEMENT" << file_data[elementsize] << endl;
    		
     // while(in >> file_data[elementsize++] && elementsize <= arraysize)
    //	  ;
    	  for(;in>>file_data[elementsize] && elementsize < arraysize;elementsize++);
    
      if(elementsize > arraysize+1)
      {
      elementsize = -1;
      cout << "There are too many elements for this array\n";
      }  
      
       return elementsize;
    }
    
    
    /********************************************************************************
     * PURPOSE			:Determines how many numbers in file are above average		*
     * PASSED IN		:file_data[],count,avg										*
     * RETURNED			:count_abv												    *
     *******************************************************************************/ 
    
    
    int count_abv_avg(int file_data[],int count,double avg)
    {
    	int count_abv = 0;
    	for(int i = 0;i < count;i++)
    		if(file_data[i] > avg)
    			count_abv++;
    	return count_abv;
    }
    
    /********************************************************************************
     * PURPOSE			:determines the smallest number in the file					*
     * PASSED IN		:file_data, count											*
     * RETURNED			:smallest												    *
     *******************************************************************************/ 
    
    
    int smallest_number(int file_data[],int count)
    {
    	int smallest = file_data[0];
    	for(int i = 0;i < count;i++)
    		if(smallest > file_data[i])
    			smallest = file_data[i];	
    	cout << "\nThis is the smallest number in the file:\t" << smallest << endl;
    	return smallest;
    }
    Last edited by ssjnamek; 09-20-2005 at 05:14 PM.
    hooch

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > for(;in>>file_data[elementsize] && elementsize < arraysize;elementsize++);
    You should change this to:
    Code:
    	  for(;elementsize < arraysize && in>>file_data[elementsize];elementsize++);
    Otherwise you may be storing in the 99th element, but the array only runs from 0-98.

    > if(elementsize > arraysize+1)
    And I believe this should be:
    Code:
      if(elementsize > arraysize)

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    hmm thats rather picky considering its an && but none the less i tried it and it doesnt die however when there is a file 0-99 it skips the 99 or the 100th element. so i changed it to

    elementsize <= arraysize and it crashes. though it does this time read the 99 or 100th element.

    the logic looks like it would work so i dont get why its not working but thats why im posting lol



    this isnt needed for the grade apparently but i didnt know that but it crashes with a blank file as well still
    hooch

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    It should be if (elementsize >= arraysize). That is because if the for loop was exited because you read in the maximum number of elements, then elementsize will be 99 (you always stop when the counter is the same as the size of the array because for a 99 element aray only posistions 0-98 are valid). Since the arraysize is also 99, then you know if the input filled the array if the elementsize is equal to the arraysize when you are done.

    Don't forget that you cannot read 100 elements into your array since it was declared to hold only 99. Also don't forget that the 99th element will be at position 98, and position 99 is illegal.

  5. #5
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ok this is what i did i made a for and just told it read the whole file. then after wards i told it to see if elements is more than arraysize. that works then i told it print the value of count to make sure it passed ok and its a -1 but it crashes on closing.

    the rest of the program works fine it tells me if there is a file, if its empty and if there is enough spaces it adds ok. with arraysize being set to 100.

    now why is stupid thing crashing when it goes over the limit?





    Code:
    int load_array(ifstream& in, int file_data[], int arraysize)
    {
        int elementsize = 0;
    	//in >> file_data[0];
    	//cout << file_data[0];
    	
    	
    	
    		if(!(in >> file_data[elementsize]))
    		{
    			cout << "File is Empty\n";
    			elementsize = -1;
    		} 
    		else
    		elementsize++;
            //cout << "0 ELEMENT" << file_data[elementsize] << endl;
    		
     // while(in >> file_data[elementsize++] && elementsize <= arraysize)
    //	  ;
    	 for(;in>>file_data[elementsize];elementsize++);
    
    		if(elementsize > arraysize)
      {
      cout << "There are too many elements for this array\n";
      elementsize = -1;
      } 
      
       return elementsize;
    }
    hooch

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You cannot access an array outside its bounds. If your array is declared to have 99 elements, then you can only access elements 0 through 98. If you try to access the element at position 99, you invoke undefined behavior, meaning anything can happen, including a crash.

    Try to understand which indexes of the array are being accessed by your code so you can see why your code is wrong and causes a crash. Look at my suggestion and see where you did the opposite of what I suggested, and try to understand why that didn't work. Also go back and try to understand swoopy's first suggestion and see why implementing it would fix your crash.

    The bottom line is you need to pay attention to which indexes you use so that you don't go over the array bounds, otherwise you will get a crash, or worse - a silently incorrect program.

  7. #7
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    oh ok i got it to work i beleive i got confused cause i kept changing numbers around since at one point or another it seemed to skip the second element when printing it and that was in the middle of me trying to figure out why it was crashing.

    although as to whether i understand this completely im going to defently mess with it some more im sure. though it does make sense must make sure elementsize stays lower and never equals arraysize. though i always thought it could equal thats why i was having a hard time. i didnt know you had to set it above intentially cause of that possibly one reason i was way off. which is probably why i removed that equal sign and went in a total opposite direction between that and frustration with it.

    also never knew the order of the condition mattered learn something new with that. though makes sense it is an expression and expressions have orders.

    and after seeing this i am officially scared if someone ever shows me this using a C++.net array
    hooch

  8. #8
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ok yes i know this thread is old but i think i just got it so it makes sense

    i have to test to make sure the elementsize is less than the arraysize followed by making sure i can still read in the file because order matters like any expression and it might read in something outside of its bounds causing said silent error or other undefinedness if it were to read the file first instead of making sure it was in the correct bounds

    however you could terminate and there could sitll be more files to be read but elementsize increments past the arraysize and kills the loop so THEN you have to make sure that arraysize and elementsize dont equal.

    yes just figured id post that lol
    hooch

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple login program - Crashes :(
    By spadez in forum C Programming
    Replies: 1
    Last Post: 03-23-2009, 04:16 PM
  2. Replies: 3
    Last Post: 02-29-2008, 01:29 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Program crashes...help Needed!!
    By butterfly in forum C++ Programming
    Replies: 4
    Last Post: 05-31-2002, 11:22 AM
  5. My program crashes with this code
    By blackwyvern in forum C++ Programming
    Replies: 3
    Last Post: 01-28-2002, 12:28 AM