Access Violation (Segmentation Fault)

티파니 레 시프

나는 두 개의 클래스 (약속, 일정)와 운전 기사 (메인)가 있습니다.

main.cpp :

#include <iostream>
#include "schedule.h"
#include "appointment.h"

using namespace std;

int main()
{
    schedule mySch2("hello");

    appointment myAppt(100002,"appointment",10,1,2013);
    myAppt.printS(cout,2);

    mySch2.addtoSchedule(myAppt);


    system("PAUSE");
    return EXIT_SUCCESS;
}

schedule.h

#ifndef SCHEDULE_H
#define SCHEDULE_H

#include<iostream>
#include "appointment.h"

using namespace::std;
const int SCH_ENTRIES = 10;
class schedule
{
      public:
             schedule(void);
             schedule(const char *p);
             bool addtoSchedule(const appointment &);

      private:
              char title[40];
              int count;
              appointment appointmentArray[SCH_ENTRIES];
};
#endif

schedule.cpp

#include "schedule.h"
#include "appointment.h"
#include <iostream>

using namespace::std;

schedule::schedule(void)
{
}
schedule::schedule(const char *p)
{
    strcpy(title, p);
    count = 0;
    cout << title << endl;
    cout << count << endl;
    cout << "----" << endl;
}

bool schedule::addtoSchedule(const appointment & myAppt)
{
    cout << appointmentArray[0].getDay();
    return false;
}

reservation.h (나는 이것을 쓰지 않았습니다, 이것은 제공되었습니다)-이 질문에 대해 그다지 중요하지 않습니다

#ifndef APPOINTMENT_H
#define APPOINTMENT_H

    #include <fstream>
    #include <cstring>

    using std::ostream;

    //  The Designer decides upon the following data and actions (i.e. Functions)
    //  and places the class in the file appointment.h

    class appointment
    {
        public:

            appointment(void);                                              // default constructor
            appointment(long, const char [],int d, int m, int y);           // 5 argument constructor
            appointment(const appointment &);                               // copy constructor

            void keyBoardInput(void);                                       // Assume no blanks in the desc

            long getSource(void) const;                                     // return source
            void setSource(long);                                           // change source

            void setMonth(int);
            void setDay(int);
            void setYear(int);

            int getMonth(void) const;
            int getDay(void) const;
            int getYear(void) const;

            const char *getDescription(void) const;                         // return the address of the description
            void changeDescription(const char *) ;                          // change an existing description

            void copyTo(appointment &) const;                               // copy invoking instance to parameter

            void incrementDate (void);                                      // advance the date by ONE day
                                                                            // You can assume 30 days in each month

            void printS(ostream &, int dateFormat) const;   // print all fields
            // dateFormat == 1   month/day/year
            // dateFormat == 2   day/month/year

            ~appointment();               // destructor - indicate the address
                                          //    of the variable that is leaving

            private:

            void setDescription(const char *);  //  used to allocated memory

            // data
            long source;          // id of the person scheduling the appointment
            char * desc;          // description of the appointment - Dynamic Data

            int  day;             // day, month, and year when the appointment
            int  month;           // will happen
            int  year;
    };

#endif

reservation.cpp (나는 이것을 쓰지 않았고 이것은 제공되었습니다)-이 질문에 대해 중요하지 않습니다.

#include "appointment.h"

#include <iostream>

using std::cin;
using std::cout;

appointment::appointment()
{
    day = 0;
    cout << "default appt\n";
}

appointment::appointment(long lSource, const char cDescription[], int d, int m, int y)
{
    source = lSource;
    day = d;
    month = m;
    year = y;
    setDescription(cDescription);
}
appointment::appointment(const appointment & aToCopy)
{
    source = aToCopy.getSource();
    day = aToCopy.getDay();
    month = aToCopy.getMonth();
    year = aToCopy.getYear();
    setDescription(aToCopy.getDescription());
}


void appointment::setDescription(const char * cSource)
{
    if (desc != NULL) free (desc);

    if (cSource == NULL)
        return;

    desc = (char *)malloc (strlen (cSource) + 1);
    strcpy(desc, cSource);
}

long appointment::getSource(void) const
{
     return source;
}

void appointment::setSource(long lSource)
{
     source = lSource;
}

void appointment::setMonth(int iMonth)
{
     month = iMonth;
}

void appointment::setDay(int iDay)
{
     day = iDay;
}

void appointment::setYear(int iYear)
{
     year = iYear;
}

int  appointment::getMonth(void) const
{
     return month;
}

int  appointment::getDay(void)   const
{
     return day;
}

int  appointment::getYear(void)  const
{
     return year;
}

//return the address of the description
const char * appointment::getDescription(void) const
{
     return desc;
}

//change an existing description
void appointment::changeDescription(const char * cDescription)
{
    setDescription(cDescription);
}

void appointment::copyTo(appointment &p) const
{
    p.source = source;
    p.day = day;
    p.month = month;
    p.year = year;
    p.setDescription(desc);
}

void appointment::incrementDate(void)
{
    int days;

    switch (month)
    {
        case 1: // Jan: 31 Days
        case 3: // Mar: 31 Days
        case 5: // May: 31 Days
        case 7: // Jul: 31 Days
        case 10: // Oct: 31 Days
        case 12: // Dec: 31 Days
            days = 31;
            break;

        case 4: // Apr: 30
        case 6: // Jun: 30
        case 8: // Aug: 30
        case 9: // Sep: 30
        case 11: // Nov: 30
            days = 30;
            break;

        case 2: // Feb: 28/29 Days (Depends on year modulus 4 a modulus 100).
            days = !(year % 4) || !(year % 100) ? 29 : 28;
            break;
    }

    day++;

    if (day > days)
    {
        month++;
        day = 1;

        if (month > 12)
        {
            month = 1;
            year++;
        }
    }
}

void appointment::printS(ostream &out, int dateFormat) const
{
    if (dateFormat == 1)
    {
        out << month << "/" << day << "/" << year << "\n";
    }
    else if (dateFormat == 2)
    {
        out << day << "/" << month << "/" << year << "\n";
    }
    else
        out << "Unsupported dateFormat parameter specified (should be 1 or 2).";
}

appointment::~appointment()
{
    if (desc != NULL)
    {
        free (desc);
        desc = NULL;
    }
}

void appointment::keyBoardInput()
{
    char temp[1024];

    cout << "Please type the description: ";
    cin.getline (temp, sizeof(temp) - 1, '\n');
    cout << std::endl;

    setDescription(temp);
}

주 드라이버가 mySch2.addtoSchedule (myAppt)을 호출 할 때 내 오류가 발생합니다.

scheduleArray [0] .getDay () 내부의 줄을 주석 해제하면 모든 것이 실행되고 세분화 오류없이 잘 작동합니다. 해당 줄의 주석이 제거 되 자마자 런타임 중에 오류가 발생합니다 (충돌 후 디버거로 이동하여 프로그램을 단계별로 실행).

WhozCraig

당신은 초기화되지 않습니다 descnullptr클래스 appointment호출하기 전에 setDescription. 이것은 두 생성자 모두에서 발생합니다. 이니셜 라이저 목록 사용 방법 알아보기 :

appointment::appointment()
    : source(), desc(), day(), month(), year()
{
    cout << "default appt\n";
}

appointment::appointment(long lSource, const char cDescription[], int d, int m, int y)
    : source(lSource), desc(), day(d), month(m), year(y)
{
    setDescription(cDescription);
}

appointment::appointment(const appointment & aToCopy)
    : source(aToCopy.getSource())
    , desc()
    , day(aToCopy.getDay())
    , month(aToCopy.getMonth())
    , year(aToCopy.getYear())
{
    setDescription(aToCopy.getDescription());
}

왜 잘못 했습니까?

초기화하지 않으면의 값 desc이 불확실하므로 역 참조 할 정의되지 않은 동작 이므로 free.

void appointment::setDescription(const char * cSource)
{
    if (desc != NULL) free (desc); // desc contains non-null garbage.

    if (cSource == NULL)
        return;

    desc = (char *)malloc (strlen (cSource) + 1);
    strcpy(desc, cSource);
}

즉, std::string대신 a 사용하는 것이 좋습니다. 이 클래스의 복사-컨스트럭터가 완전히 사라지고 기본 생성자는 사소합니다.

malloc()C ++ 프로그램에서 사용 하는 것에 대한 의견은이 포럼에서 이미 모든 의견이 죽을 정도로 치명적이기 때문에 예약되어 있습니다 (그리고 나는 일반적인 의견에 동의합니다).

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

A* Implementation in C, Segmentation fault

분류에서Dev

Segmentation Fault - GNU C

분류에서Dev

Segmentation fault in Assembly and string

분류에서Dev

Malloc to struct; segmentation fault

분류에서Dev

Segmentation Fault in hsearch

분류에서Dev

Strcpy Segmentation Fault C

분류에서Dev

Segmentation Fault? Why?

분류에서Dev

Strange segmentation fault in code

분류에서Dev

Segmentation Fault on return statement

분류에서Dev

glGenBuffers crashing with Segmentation fault

분류에서Dev

Struct causing segmentation fault

분류에서Dev

Resetting Variable : Segmentation fault

분류에서Dev

Segmentation fault in sorting algorithm

분류에서Dev

Segmentation Fault While Sorting - Malloc

분류에서Dev

Fractional Knapsack Algorithm segmentation fault

분류에서Dev

Segmentation fault on reboot Ubuntu 12.04

분류에서Dev

C Segmentation fault using strtok

분류에서Dev

python Segmentation fault (core dumped)

분류에서Dev

Segmentation fault in sigaction signal handler

분류에서Dev

Segmentation fault on reverse string function

분류에서Dev

Segmentation fault with flex bison and yyparse

분류에서Dev

Why is the segmentation Fault error occuring

분류에서Dev

Depth first Minimax Segmentation Fault

분류에서Dev

while ... readdir causing segmentation fault

분류에서Dev

Graph adjacency matrix segmentation fault

분류에서Dev

OpenGL, Access violation

분류에서Dev

Running bash does "segmentation fault core dumped"

분류에서Dev

Segmentation fault in recursive Binary Search Algorithm in C

분류에서Dev

Segmentation fault upon insertion into binary search tree