Solved

Coredump with classes + float?

Posted on 2002-03-16
9
255 Views
Last Modified: 2010-04-01
hey,
i am a computer science student and i have encountered a problem where i get a coredump when using variables of type float or double in classes. i get a coredump when on unix and strange values like -9.3234e1324 in windows.
this is the second program that i have attempted to write and ran into this problem. i am pasting a sample of a program i wrote that might help you in helping me.

// main.cpp

#include "List.h"

int choice(int menu);

//contains an incomplete menu
int main()
{
     int menu;

     do
     {
          cout << "Choose from the following\n";
          cout << "1: Compute the mean.\n";
          cout << "2: Compute the median.\n";
          cout << "3: Compute the mode.\n";
          cout << "4: Compute the standard deviation.\n";
          cout << "5: Search for a number in the list.\n";
          cout << "6: Sort the list.\n";
          cout << "7: Read a file into memory.\n";
          cout << "8: Save the list.\n";
          cout << "9: Add a number to the list.\n";
          cout << "10: Remove a number from the list.\n";
          cout << "0: Exit the program.\n";

          cout << "Enter your choice: ";
          cin >> menu;

          choice(menu);
     }while (menu != 0);

return 0;
}

int choice(int menu)
{
     List list;
     if (menu == 7) list.readFile();
     else if (menu == 8) list.saveFile();
     else if (menu == 9) list.add();
     else return 0;

     return 0;
}
------------------------------------------------------
// List.h

#include <iostream.h>
#include <fstream>
#include <string>

using namespace std;

#ifndef LIST_H
#define LIST_H

class List
{
public:
     void readFile();
     void saveFile();
     void add();

private:
     char* inputFilename;
     char* outputFilename;
     int* array;
     bool fileLoaded;
     int arraySize;
};

#endif LIST_H
------------------------------------------------
// List.cpp

#include "List.h"

//read a file with a list of numbers
void List::readFile()
{
     inputFilename = new char;
     cout << "Enter input filename: ";
     cin >> inputFilename;

     ifstream inputFile;
     inputFile.open(inputFilename);

     cout << "Enter array size: ";
     cin >> arraySize;

     array = new int[arraySize];

     int i = 0;
     while (i < arraySize)
     {
          inputFile >> array[i];
          i++;
     }          

}

//saves a file with a list of numbers
void List::saveFile()
{
     outputFilename = new char;

     cout << "Enter output filename: ";
     cin >> outputFilename;

     ofstream outputFile;
     outputFile.open(outputFilename);

     int i = 0;
     while(i < arraySize)
     {
          outputFile << array[i] << endl;
     }
}

//adds a number to the array
void List::add()
{
     int* arrayTemp = array;
     array = new int[arraySize++];

     array = arrayTemp;
     delete arrayTemp;

     cout << "Enter # to add to list: ";
     cin >> array[arraySize++];

     arraySize++;
}

i also get a different problem after loading the text file and setting a dynamic array to the values in the file. after i exit the function which reads the file, the values in the dynamic array disappear. so if i call the read function and successfully get information from a file and then try to call the function for saving a text file the values in the array dont exist. i know this because i put debug cout statements everywhere and once the program leaves the read function the values in the array are gone.

maybe i am using classes incorrectly.. i dont know.. thats why i'm here
0
Comment
Question by:grfik
  • 5
  • 3
9 Comments
 
LVL 1

Expert Comment

by:lidorc
Comment Utility
Hi grfk,
Try to point out the exact line which make a problem.
But first, some problems you should fix:
You wrote:
---
void List::readFile()
{
    inputFilename = new char;
    cout << "Enter input filename: ";
    cin >> inputFilename;
---
and in the save file you did the same. inputFileName is suppose to be a char array and not just ONE CHAR. you should define:
   char inputFileName[80];
and you shouldn't use new when it isn't necessary.

Second, in the add() function, your array is full of garbage because you delete it!! look at it carefully..
About this "array" data member, you should initialize it in the "member initialization list" or in the constructor to NULL and then before you want to assign it a new value you should delete[] the old char array and only then assign it a new one
0
 

Author Comment

by:grfik
Comment Utility
the exact line where the problem with the core dump occurs is the first time i access a double or float variable which is a class member. in the code i listed above the array is of type int, but i would like it to be float.
0
 

Author Comment

by:grfik
Comment Utility
i tried intializing the array but i get a runtime another runtime error. and wat do u mean delete[] the old char array?
0
 
LVL 2

Expert Comment

by:LoungeLizard
Comment Utility
Apart from the problems mentioned above, your add() function of List class is a complete mess:

1. arraySize is un-intiliazed which means it could hold ANY value. Initiliazation should be done in the constructor of List, something like:

List::List() : arraySize(0)
{}

or

List::List()
{
  arraySize = 0;
}

2. You increase arraySize 3 times! This should only be done once.

3. Remember that when you delete the "old" array then you delete all the values along with that. So when you do this kind of thing you'll first have to copy the old values across to the new array.

void List::add()
{
    //create new array with size one larger than previously
    int* arrayTemp = new int[arraySize+1];

    // copy all the old values
    for (int i=0; i<arraySize; i++)
      arrayTemp[i]=array[i];

    // delete old array
    delete array;

    // point to the new array
    array = arrayTemp;

    arraySize++;

    cout << "Enter # to add to list: ";

    // get new value
    cin >> array[arraySize];

}

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 2

Expert Comment

by:LoungeLizard
Comment Utility
One other thing : Wherever you "new" something you have to "delete" it again, failure to do this will lead to a memory leak. So, for inputFilename and outputFilename you should delete the allocated memory at the end of the calls. Also, it is a good idea to delete "array" during destruction of class List . Although it might not seem neccesary now (because the object of type List is  destroyed upon termination of the program, and the memory de-allocated automatically ) it might not always be the case
0
 

Author Comment

by:grfik
Comment Utility
i didnt know that arraySize is incremented when i use it in " = new int[arraySize++]"

its not a complete program so i planned on calling the read function everytime i ran the program before i call the add function, so arraySize would have a value. but can u tell me why the dynamic array i create in function readFile loses the values it store at the end of the function?
and the little problem with float types and coredumps
0
 

Author Comment

by:grfik
Comment Utility
i tried intializing the array and arraySize in a constructor but when i put cout statements in different functions to see if the values set be the read function are still in the array it outputs values like -912343214
0
 
LVL 2

Accepted Solution

by:
LoungeLizard earned 100 total points
Comment Utility
arraySize++ means arraySize = arraySize + 1 i.e. you increase the value by one each time.

There are some other problems also that I notice now:

1. The declaration of list should not be in choice(). If you put it there then the object list of type List will be LOCAL to choice() only, which means that it is visible inside choice() only and is destroyed each time the function choice() is terminated. A new object is created the next time you enter the choice() again.

2. The "delete array" statement I have above might cause problems because array might not be pointing to anything valid, so we have to build in some kind of check here.

3. If have increased the value of arraySize in the wrong place. It should be done AFTER the assignment of the value, because the array elements are numbered 0 to arraySize-1. So, for example, if arraySize = 3 and when add a new element it should be added at position 3 and arraySize increased to 4.

4. Your saveFile() function will not work since you never increase i, which means you'll get an infinite loop.

Anyway, here is the whole reworked thing. Have a look and let me know if there are problems:

#include <iostream.h>
#include <fstream>
#include <string>

using namespace std;

class List
{
public:
    List() : arraySize(0), array(0)
    {}

    void readFile();
    void saveFile();
    void add();

private:
    char inputFilename[80];
    char outputFilename[80];
    int* array;
    bool fileLoaded;
    int arraySize;
};

//read a file with a list of numbers
void List::readFile()
{
    cout << "Enter input filename: ";
    cin >> inputFilename;

    ifstream inputFile;
    inputFile.open(inputFilename);

    cout << "Enter array size: ";
    cin >> arraySize;

    array = new int[arraySize];

    int i = 0;
    while (i < arraySize)
    {
         inputFile >> array[i];
         i++;
    }          

}

//saves a file with a list of numbers
void List::saveFile()
{
    cout << "Enter output filename: ";
    cin >> outputFilename;

    ofstream outputFile;
    outputFile.open(outputFilename);

    int i = 0;
    while(i < arraySize)
    {
         outputFile << array[i] << endl;
         i++;
    }
}

//adds a number to the array
void List::add()
{
   //create new array with size one larger than previously
   int* arrayTemp = new int[arraySize+1];

   // copy all the old values
   for (int i=0; i<arraySize; i++)
   {
     arrayTemp[i]=array[i];
     cout << i << " - " << arrayTemp[i] << endl;
   }
                                         
   // delete old array
   if(array)
      delete array;

   // point to the new array
   array = arrayTemp;

   cout << "Enter # to add to list: ";

   // get new value
   cin >> array[arraySize];

   arraySize++;

}


int choice(List * list, int menu)
{
    if (menu == 7) list->readFile();
    else if (menu == 8) list->saveFile();
    else if (menu == 9) list->add();
    else return 0;

    return 0;
}

int main()
{
    int menu;
    List list;

    do
    {
         cout << "Choose from the following\n";
         cout << "1: Compute the mean.\n";
         cout << "2: Compute the median.\n";
         cout << "3: Compute the mode.\n";
         cout << "4: Compute the standard deviation.\n";
         cout << "5: Search for a number in the list.\n";
         cout << "6: Sort the list.\n";
         cout << "7: Read a file into memory.\n";
         cout << "8: Save the list.\n";
         cout << "9: Add a number to the list.\n";
         cout << "10: Remove a number from the list.\n";
         cout << "0: Exit the program.\n";

         cout << "Enter your choice: ";
         cin >> menu;

         choice(&list, menu);
    }while (menu != 0);

return 0;
}



0
 

Author Comment

by:grfik
Comment Utility
wow, it worked great loungelizard.. and it also solved the problem of the coredump
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now