Getting a segmentation fault as soon as I run my program?

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 616 Views - Last Post: 11 July 2013 - 08:40 PM Rate Topic: -----

#1 jordannn15  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 215
  • Joined: 06-July 12

Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 01:25 PM

Okay, so I don't get any errors but as soon as I run my program it will stall for like a second and then give me a segmentation fault (core dumped). Why is this?

Backtrace: #0 0x00012670 in Date::Date (this=<error reading variable: Cannot access memory at address 0x11c15a9c>,
nameset=<error reading variable: Cannot access memory at address 0x11c15aa0>) at date.cc:13
#1 0x0001116c in birthday::birthday (this=<error reading variable: Cannot access memory at address 0x11c15a90>) at birthday.cc:6


//My professor wrote this file

#include <iostream>
#include <ctype.h>

#ifndef DATE_H
#define DATE_H
// an exception if the date entered is invalid for the month
class bad_day{
    public:
        bad_day(){monthnum=daynum=0;}
        bad_day(int m, int d)
                {monthnum = m, daynum=d;}
        void msg(){std::cerr<<monthnum<<" has no day "<<daynum<<std::endl;}
    private:
        int monthnum, daynum;
};

// an exception for an invalid month number
class bad_month{
    public:
        bad_month(){monthnum = 0;}
        bad_month(int m){monthnum = m;}
        void msg(){std::cerr<<monthnum<<" is an invalid month number.\n";}
    private:
        int monthnum;
};

// a simple class for holding dates
class Date{
    public:
        Date(bool nameset=1);
        Date(int d,int m,int y);

    // outputs the date
        friend std::ostream& operator <<(std::ostream& outs, Date d);

    //inputs the date
        friend std::istream& operator >>(std::istream& ins, Date& d);

/**************************************************
        COMPARSION OPERATORS
**************************************************/

        friend bool operator > (const Date& d1, const Date& d2);

        friend bool operator < (const Date& d1, const Date& d2);

        friend bool operator == (const Date& d1, const Date& d2);

        friend bool operator != (const Date& d1, const Date& d2);

        friend bool operator <= (const Date& d1, const Date& d2);

        friend bool operator >= (const Date& d1, const Date& d2);

        std::string get_name()const;

        void toggle_name_on();

        void set_name(std::string nname);

private:
   int day;
   int month;
   int year;
   int daysallowed[13];
   std::string name;
   bool nameon;
};

#endif



//My professor also wrote this file
//date.cc file

#include "date.h"

using namespace std;
// default constructor
Date::Date(bool nameset){
        day=month=year=0;
    // permissable days for each month are loaded into an array
         daysallowed[0] = 0;
         daysallowed[1] = 31;
         daysallowed[2] = 29;
         daysallowed[3] = 31;
         daysallowed[4] = 30;

         daysallowed[5] = 31;
         daysallowed[6] = 30;
         daysallowed[7] = 31;
         daysallowed[8] = 31;
         daysallowed[9] = 30;
         daysallowed[10] = 31;
         daysallowed[11] = 30;
         daysallowed[12] = 31;

        nameon=nameset;}

// constructor that takes three arguments
Date::Date(int d,int m, int y):day(d),month(m),year(y)
        {

    // permissable days for each month are loaded into an array
         daysallowed[0] = 0;
         daysallowed[1] = 31;
         daysallowed[2] = 29;
         daysallowed[3] = 31;
         daysallowed[4] = 30;
         daysallowed[5] = 31;
         daysallowed[6] = 30;
         daysallowed[7] = 31;
         daysallowed[8] = 31;
         daysallowed[9] = 30;
         daysallowed[10] = 31;
         daysallowed[11] = 30;
         daysallowed[12] = 31;}

// output operator, overloaded as a friend function
ostream& operator <<(ostream& outs, Date d){
    outs<<d.month<<'/'<<d.day<<'/'<<d.year;
    if(d.nameon)outs<<endl<<d.name;
    return outs;
}

// input operator, overloaded as a friend
istream& operator >>(istream& ins, Date& d){
   bool flag = false;
   string junk;

   ins>>d.month;
// if an invalid month is detected throw a bad_month
       if(d.month < 1 || d.month > 12){
                getline(ins,junk); // eat the rest of the line
                throw (bad_month(d.month));
        }
// if the read has failed because of eof exit funtion
   if(ins.eof()) return ins;

   if(ins.peek() == '/') ins.ignore();
   ins>>d.day;
// if an invalid day is detected throw a bad_day
        if(d.day < 1  || d.day > d.daysallowed[d.month]){
                getline(ins,junk); // eat the rest of the line
                throw (bad_day(d.month, d.day));
        }
  if(ins.eof()) return ins;
  if(ins.peek() == '/') ins.ignore();

   ins>>d.year;
   if(d.nameon){
        if(ins==cin) cout<<"Name: ";
        if(ins.peek() == '\n') ins.ignore();
        getline(ins, d.name);
   }
   return ins;
}

// return whether or not d1 is greater than d2
bool operator > (const Date& d1, const Date& d2){
        if(d1.year != d2.year)
          return (d1.year > d2.year);
        else if(d1.month != d2.month)
          return(d1.month > d2.month);
        else
          return (d1.day > d2.day);
}

// return whether or not d1 is less than d2
bool operator < (const Date& d1, const Date& d2){
        if(d1.year != d2.year)
          return (d1.year < d2.year);
        else if(d1.month != d2.month)
          return(d1.month < d2.month);
        else
          return (d1.day < d2.day);
}

// return whether or not d1 equals d2
bool operator == (const Date& d1, const Date& d2){
        return(d1.year == d2.year && d1.month == d2.month &&
               d1.day == d2.day);
}

// return whether or not d1 is not equal to d2
bool operator != (const Date& d1, const Date& d2){
        return(!(d1.year == d2.year && d1.month == d2.month &&
               d1.day == d2.day));

}

// return whether or not d1 is less than or equal to d2
bool operator <= (const Date& d1, const Date& d2){
        return (d1 == d2 || d1 < d2);
}

// return whether or not d1 is greater than or equal to d2
bool operator >= (const Date& d1, const Date& d2){
        return (d1 == d2 || d1 > d2);
}

std::string Date::get_name()const
        {return name;}

void Date::toggle_name_on()
        {nameon=!nameon;}

void Date::set_name(std::string nname)
        {if(nameon)
            name = nname;
         else
            cout<<"Name facility is turned off.\n";
        }



//I wrote this

#ifndef BIRTHDAY_H
#define BIRTHDAY_H
#include <iostream>
#include "date.h"

class birthday {
public:
        birthday();
        ~birthday();

        void resize();
        birthday(const birthday& other);
        void operator =(const birthday& other);

        void start() {current_index = 0;}
        void advance() {current_index++;}
        bool is_index() {return current_index < used;}
        Date current() {return current_index;}

        void insert(const Date& item);
        void attach(const Date& item);
        void remove_current();
        void remove_specific(Date& item);
        void display();

        void load_from_file(std::istream& ins);
        char menu();
        void save_to_file(std::ostream& outs);

private:
        Date *ptr;
        std::size_t capacity;
        std::size_t used;
        std::size_t current_index;
};

#endif



//I also wrote this
//birthday.cc file

#include "date.h"
#include "birthday.h"
#include <iostream>

birthday::birthday(){
        Date d[capacity];
        ptr = d;
        capacity = 5;
        used = 0;
        current_index = 0;
}

birthday::~birthday(){
        delete []ptr;
}

void birthday::resize(){
        Date *tmp;
        tmp = new Date[capacity + 5];

        std::copy(ptr, ptr + used, tmp);
        capacity += 5;

        delete []ptr;
        ptr = tmp;
}

birthday::birthday(const birthday& other){
        ptr = new Date[capacity];
        std::copy(ptr, ptr + other.used, ptr);

        capacity = other.capacity;
        used = other.used;
        current_index = other.current_index;
}

void birthday::operator =(const birthday& other){
        if(&other == this) return;

        delete []ptr;
        ptr = new Date[capacity];
        std::copy(ptr, ptr + used, ptr);

        capacity = other.capacity;
        used = other.used;
        current_index = other.current_index;
}

void birthday::insert(const Date& item){
        if(used < capacity){
                ptr[current_index - 1] = item;
                used++;
        }else{
                resize();
                ptr[current_index - 1] = item;
                used++;
        }
}

void birthday::attach(const Date& item){
        if(used < capacity){
                ptr[current_index + 1] = item;
                used++;
        }else{
                resize();
                ptr[current_index + 1] = item;
                used++;
        }
}

void birthday::remove_current(){
        if(used < capacity){
                ptr[current_index] = ptr[current_index + 1];
                used--;
        }else{
                resize();
                ptr[current_index] = ptr[current_index + 1];
                used--;
        }
}

void birthday::remove_specific(Date& item){
        std::cout << "What date do you want to remove?\n\n";
        std::cout << "Enter the date ->   ";
        std::cin >> item;

        for(start(); is_index(); advance()){
                if(ptr[current_index] == item){
                        ptr[current_index] = ptr[current_index + 1];
                        used--;
                }
        }
}

void birthday::display(){
        for(start(); is_index(); advance())
                std::cout << ptr[current_index] << std::endl;
}

void birthday::load_from_file(std::istream& ins){
        Date tmp;

        while(ins >> tmp)
                insert(tmp);
}

char birthday::menu(){
        char choice;
        Date item;

        do
        {
                std::cout << "1. Insert date.\n";
                std::cout << "2. Remove current date.\n";
                std::cout << "3. Remove specific date.\n";
                std::cout << "4. Display all dates.\n";
                std::cout << "5. Quit.\n\n";
                std::cout << "Enter your choice ->   ";
                std::cin >> choice;

        if(choice == '1')
                insert(item);
        else if(choice == '2')
                remove_current();
        else if(choice == '3')
                remove_specific(item);
        else if(choice == '4')
                display();
        else if(choice == '5')
                std::cout << "Goodbye.\n";
        else
                std::cout << choice << " is invalid. Choose 1 - 5.\n";
        }while(choice != '5');

        return choice;
}

void birthday::save_to_file(std::ostream& outs){
        for(start(); is_index(); advance())
                outs << ptr[current_index] << std::endl;
}



//I wrote this too
//main.cc

#include "date.h"
#include "birthday.h"
#include <iostream>
#include <fstream>

int main(){
        birthday day;

        std::ifstream ifs("birthdays.dat");
        if(!ifs.fail())
                day.load_from_file(ifs);
        ifs.close();

        day.menu();

        std::ofstream ofs("birthdays.dat");
        if(!ofs.fail())
                day.save_to_file(ofs);
        ofs.close();

        return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Getting a segmentation fault as soon as I run my program?

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3652
  • View blog
  • Posts: 11,421
  • Joined: 05-May 12

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 03:01 PM

If you run your program in a debugger, then it will take you right to the line of code that is causing the segmentation fault. Otherwise, you'll hear from jimblumberg that you should post the minimal amount of code that reproduces your problem.
Was This Post Helpful? 0
  • +
  • -

#3 jordannn15  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 215
  • Joined: 06-July 12

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 03:11 PM

View PostSkydiver, on 11 July 2013 - 03:01 PM, said:

If you run your program in a debugger, then it will take you right to the line of code that is causing the segmentation fault. Otherwise, you'll hear from jimblumberg that you should post the minimal amount of code that reproduces your problem.


I ran it in debugger mode and it will show me the first line which is birthday day for my object and then it gives me this message:
Breakpoint 1, main () at main.cc:7
7 birthday day;
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x00012670 in Date::Date (this=<error reading variable: Cannot access memory at address 0x11c15a9c>,
nameset=<error reading variable: Cannot access memory at address 0x11c15aa0>) at date.cc:13
13 Date::Date(bool nameset){
Was This Post Helpful? 0
  • +
  • -

#4 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1102
  • View blog
  • Posts: 4,597
  • Joined: 09-June 09

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 03:15 PM

You are stepping over the constructor of your birthday object. Try stepping "into" the constructor to see what is really happening.

To step into use the "s" command in gdb.

This post has been edited by jjl: 11 July 2013 - 03:16 PM

Was This Post Helpful? 0
  • +
  • -

#5 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 838
  • View blog
  • Posts: 2,462
  • Joined: 20-March 10

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 03:23 PM

You are using

capacity before its initialised

birthday::birthday(){
 Date d[capacity];


try moving capacity =5;

to above Date d[capacity];

Snoopy.
Was This Post Helpful? 2
  • +
  • -

#6 jordannn15  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 215
  • Joined: 06-July 12

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 03:24 PM

Okay when I step into my constructor and then hit next one time it gives me:
Breakpoint 1, main () at main.cc:7
7 birthday day;
(gdb) s
birthday::birthday (this=0xffbffa30) at birthday.cc:5
5 birthday::birthday(){
(gdb) n
6 Date d[capacity];
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x00011134 in birthday::birthday (this=0xffbffa30) at birthday.cc:6
6 Date d[capacity];

Okay thanks that moving the capacity above the other statement worked.

This post has been edited by jordannn15: 11 July 2013 - 03:25 PM

Was This Post Helpful? 1
  • +
  • -

#7 jimblumberg  Icon User is offline

  • member icon


Reputation: 4234
  • View blog
  • Posts: 13,300
  • Joined: 25-December 09

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 04:34 PM

Please show your modified code.

This should still be causing problems, it doesn't matter where you initialize capacity:

birthday::birthday(){
        Date d[capacity];

C++ doesn't allow VLAs (Variable Length Arrays). Array sizes must be constant. Also since you're not using new in your default constructor, when the class goes out of scope your destructor should fail.


Jim
Was This Post Helpful? 1
  • +
  • -

#8 jordannn15  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 215
  • Joined: 06-July 12

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 04:58 PM

Okay, it will let me insert a date fine but when I try to display all dates it will give me a Seg fault again. I can't really test anything else in my menu until I get this to work so help please?


#ifndef BIRTHDAY_H
#define BIRTHDAY_H
#include <iostream>
#include "date.h"

class birthday {
public:
        birthday();
        ~birthday();

        void resize();
        birthday(const birthday& other);
        void operator =(const birthday& other);

        void start() {current_index = 0;}
        void advance() {current_index++;}
        bool is_index() {return current_index < used;}
        Date current() {return current_index;}

        void insert(Date& item);
        void attach(Date& item);
        void remove_current();
        void remove_specific(Date& item);
        void display();

        void load_from_file(std::istream& ins);
        int menu();
        void save_to_file(std::ostream& outs);

private:
        Date *ptr;
        std::size_t capacity;
        std::size_t used;
        std::size_t current_index;
};

#endif




#include "date.h"
#include "birthday.h"
#include <iostream>

birthday::birthday(){
        capacity = 5;
        Date d[capacity];
        ptr = d;
        used = 0;
        current_index = 0;
}

birthday::~birthday(){
        delete []ptr;
}

void birthday::resize(){
        Date *tmp;
        tmp = new Date[capacity + 5];

        std::copy(ptr, ptr + used, tmp);
        capacity += 5;

        delete []ptr;
        ptr = tmp;
}

birthday::birthday(const birthday& other){
        ptr = new Date[capacity];
        std::copy(ptr, ptr + other.used, ptr);

        capacity = other.capacity;
        used = other.used;
        current_index = other.current_index;
}

void birthday::operator =(const birthday& other){
        if(&other == this) return;

        delete []ptr;
        ptr = new Date[capacity];
        std::copy(ptr, ptr + used, ptr);

        capacity = other.capacity;
        used = other.used;
        current_index = other.current_index;
}

void birthday::insert(Date& item){
        if(used < capacity){
                ptr[current_index - 1] = item;
                used++;
        }else{
                resize();
                ptr[current_index - 1] = item;
                used++;
        }
}

void birthday::attach(Date& item){
        if(used < capacity){
                ptr[current_index + 1] = item;
                used++;
        }else{
                resize();
                ptr[current_index + 1] = item;
                used++;
        }
}

void birthday::remove_current(){
        if(used < capacity){
                ptr[current_index] = ptr[current_index + 1];
                used--;
        }else{
                resize();
                ptr[current_index] = ptr[current_index + 1];
                used--;
        }
}

void birthday::remove_specific(Date& item){
        for(start(); is_index(); advance()){
                if(ptr[current_index] == item){
                        ptr[current_index] = ptr[current_index + 1];
                        used--;
                }
        }
}

void birthday::display(){
        for(start(); is_index(); advance())
                std::cout << ptr[current_index] << std::endl;
}

void birthday::load_from_file(std::istream& ins){
        Date tmp;

        while(ins >> tmp)
                insert(tmp);
}

int birthday::menu(){
        int choice;
        Date item;

        do
        {
                std::cout << "1. Insert date.\n";
                std::cout << "2. Remove current date.\n";
                std::cout << "3. Remove specific date.\n";
                std::cout << "4. Display all dates.\n";
                std::cout << "5. Quit.\n\n";
                std::cout << "Enter your choice ->   ";
                std::cin >> choice;

        if(choice == 1){
                std::cout << "Enter a date ->   ";
                std::cin >> item;
        if(item > ptr[current_index])
                attach(item);
        else
                insert(item);
        }
        else if(choice == 2)
                remove_current();
        else if(choice == 3)
                remove_specific(item);
        else if(choice == 4)
                display();
        else if(choice == 5)
                std::cout << "Goodbye.\n";
        else
                std::cout << choice << " is invalid. Choose 1 - 5.\n";
        }while(choice != 5);

        return choice;
}

void birthday::save_to_file(std::ostream& outs){
        for(start(); is_index(); advance())
                outs << ptr[current_index] << std::endl;
}


Was This Post Helpful? 0
  • +
  • -

#9 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 838
  • View blog
  • Posts: 2,462
  • Joined: 20-March 10

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 05:18 PM

Hi,

Jim is right you cant use VLA's like that in C++

you would have to do something like

birthday::birthday(){
        capacity = 5;
        Date* d = new Date[capacity];
        ptr = d;

        used = 0;
        current_index = 0;
}



also insert date shouldnt that actually prompt the user to enter a date ?

Maybe Im confused.

Regards

Snoopy.
Was This Post Helpful? 1
  • +
  • -

#10 jordannn15  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 215
  • Joined: 06-July 12

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 06:02 PM

View Postsnoopy11, on 11 July 2013 - 05:18 PM, said:

Hi,

Jim is right you cant use VLA's like that in C++

you would have to do something like

birthday::birthday(){
        capacity = 5;
        Date* d = new Date[capacity];
        ptr = d;

        used = 0;
        current_index = 0;
}



also insert date shouldnt that actually prompt the user to enter a date ?

Maybe Im confused.

Regards

Snoopy.



Yes I will change that I just wrote it to test it really quick I don't know why I didn't just write it in the insert function. Also, that bit of code you put ^up there worked. It now displays the dates but it displays it as all zeros i.e. 0/0/0. Why?
Was This Post Helpful? 0
  • +
  • -

#11 jimblumberg  Icon User is offline

  • member icon


Reputation: 4234
  • View blog
  • Posts: 13,300
  • Joined: 25-December 09

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 06:02 PM

Why are you trying to create an array of Date in this class? You can only have one birth date.

Jim
Was This Post Helpful? 0
  • +
  • -

#12 jordannn15  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 215
  • Joined: 06-July 12

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 06:16 PM

I think my professor is trying to simulate something like having a bunch of your friends birthdays and names (which I know I have nothing for names but in his code there is so after it asks for the date in my part of the code it asks for the name too) in your phone or on a calendar, something like that.
Was This Post Helpful? 0
  • +
  • -

#13 jimblumberg  Icon User is offline

  • member icon


Reputation: 4234
  • View blog
  • Posts: 13,300
  • Joined: 25-December 09

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 06:44 PM

Quote

I think my professor is trying to simulate something like having a bunch of your friends birthdays and names

This seems like your birthday class should be part of another class, like maybe a person class. This person class then might have several other classes, perhaps a Date instance for the birthday, an Address class to hold the address information, a Phone class to hold the phone information, etc. Then you could create another class that would create an array of person to hold all this "Contact" information.

But with a name like "Birthday" I wouldn't expect to see an array of dates.

I think you really need to step back and review what exactly you're trying to accomplish. It looks like you need to do a little more planning before you actually start throwing together code.


Jim

This post has been edited by jimblumberg: 11 July 2013 - 06:46 PM

Was This Post Helpful? 0
  • +
  • -

#14 jordannn15  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 215
  • Joined: 06-July 12

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 06:57 PM

No this is my assignment and that was just the name I thought of first. I didn't really think the name meant that much?
Was This Post Helpful? 0
  • +
  • -

#15 jimblumberg  Icon User is offline

  • member icon


Reputation: 4234
  • View blog
  • Posts: 13,300
  • Joined: 25-December 09

Re: Getting a segmentation fault as soon as I run my program?

Posted 11 July 2013 - 07:38 PM

Quote

No this is my assignment and that was just the name I thought of first.

But what is your assignment? To outsiders that don't know your assignment the names of your classes and variables are very important. They help us in trying to follow your logic.

Quote

I didn't really think the name meant that much?

But names do mean a lot. That's why you should always use names that are meaningful. Meaningful names helps you and others conceptualize the problem.

After all every person only has one birthday. But a person can have many friends with different birthdays.

Jim

This post has been edited by jimblumberg: 11 July 2013 - 07:40 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2