Solved

Coredump with classes + float?

Posted on 2002-03-16
9
259 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
ID: 6873479
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
ID: 6873520
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
ID: 6873524
i tried intializing the array but i get a runtime another runtime error. and wat do u mean delete[] the old char array?
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 2

Expert Comment

by:LoungeLizard
ID: 6873625
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
 
LVL 2

Expert Comment

by:LoungeLizard
ID: 6873631
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
ID: 6874039
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
ID: 6874194
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
ID: 6874810
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
ID: 6875413
wow, it worked great loungelizard.. and it also solved the problem of the coredump
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

776 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