堆已损坏

时间:2013-07-26 08:25:58

标签: c++ input heap-corruption

在我的main函数中,我调用inputHolding 5次。它经历了几个循环然后它给我一个错误,说它在尝试读取callNumber时通常在第三个循环中已经被破坏了。我该如何修复此崩溃?

Holding* inputHolding() {
char selection;
char title[50];
int callNumber = 0;
char author[50];
char performer[50];
char format;

cout << "Enter B for book, R for recording: ";
cin >> selection;

if (selection == 'B') {
    cout << "Enter book title: ";
    cin >> title;

    cout << "Enter book author: ";
    cin >> author;

    cout << "Enter call number: ";
    cin >> callNumber;

    Book* muhbooksie = new Book(title, callNumber, author);
    return muhbooksie;
}
else  if (selection == 'R') {
    cout << "Enter recording title: ";
    cin >> title;

    cout << "Enter performer: ";
    cin >> performer;

    cout << "Enter format: (M)P3, (W)AV, (A)IFF: ";
    cin >> format;

    cout << "Enter call number: ";
    cin >> callNumber;

    Recording* muhbooksie = new Recording(title, callNumber, performer,     format);
    return muhbooksie;
}
else {
    cout << "Incorrect selection" << endl;
    return nullptr;
}
}

Book.cpp:

#include <iostream>
#include "Holding.h"
#include "Book.h"
#include "String.h"

using namespace std;

Book::Book() {

}

Book::Book(const Book& copy) : Holding(copy) {
author = new char[strlen(copy.author) + 1];

strcpy_s(author, sizeof(author), copy.author);
}

Book::Book(char* inputTitle, int inputCallNum, char* inputAuthor) : Holding(inputTitle,     inputCallNum) {
int len = strlen(inputAuthor) + 1;
author = new char[len];

strcpy_s(author, sizeof(author)*len, inputAuthor);
}

Book::~Book() {
delete [] author;
}

void Book::print() {
cout << "BOOK: " << author << " " << title << " " << callNumber << endl;
}

1 个答案:

答案 0 :(得分:1)

在问题的评论部分中说明了所有内容,您应该(对于Book类):

  • 重载'='运算符,
  • 实施'复制和交换'习语,
  • 并在默认构造函数中的nullptr初始化'author'并检查析构函数中的值。

这样,您的代码将更加清晰,例如,如果使用默认构造函数,析构函数将不会删除未指定的作者。