在对象构造期间缓冲太小。认为它与strcpy_s()有关

时间:2012-11-13 04:11:18

标签: c++ class constructor strcpy

我提出的代码是第三周上课的结果。我对事情有一个非常好的处理,(或者我认为),但本周专注于指针,我不知道为什么我一直得到这个错误。我一直在调试断言失败!错误以及一般的“缓冲区太小”的解释。

my error message

以下是我使用VS 2012 RC版本11.0.505221.1在Win8操作系统上编译的完整代码。与我在Linux中编译的唯一区别是我在此代码中使用strcpy_s()因为某些原因MS不喜欢strcpy()。

#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <limits>

using namespace std;

class HotelRoom
{
    char roomNumber[4];
    char guest[81];
    int roomCapacity, currentOccupants;
    double roomRate;

public:
    HotelRoom(char[], char[], int, double);
    ~HotelRoom();
    void DisplayRoom();
    void DisplayNumber();
    void DisplayName();
    int GetCapacity();
    int GetStatus();
    double GetRate();
    void ChangeStatus(int);
    void ChangeRate(double);
};

HotelRoom::~HotelRoom() {
cout << endl << endl;
cout << "Room #" << roomNumber << " no longer exists." << endl;
delete [] guest;
}

void HotelRoom::DisplayName() {
cout << guest;
}

void HotelRoom::DisplayNumber() {
cout << roomNumber;
}

int HotelRoom::GetCapacity() {
return roomCapacity;
}

int HotelRoom::GetStatus() {
return currentOccupants;
}

double HotelRoom::GetRate() {
return roomRate;
}

void HotelRoom::ChangeStatus(int occupants) {
if(occupants <= roomCapacity) {
    currentOccupants = occupants;
}
else {
    cout << endl << "There are too many people for this room. Setting occupancy to -1." << endl;
    currentOccupants = -1;
}
}

void HotelRoom::ChangeRate(double rate) {
roomRate = rate;
}

HotelRoom::HotelRoom(char room[], char guestName[], int capacity, double rate)
{
strcpy_s(roomNumber, room);     //Compiles fine with strcpy on Linux, but MS is making me use strcpy_s to compile
guestName = new char[strlen(guestName) + 1];
strcpy_s(guest, guestName);     //Same as above
roomCapacity     =  capacity;
currentOccupants = 0;
roomRate         = rate;
}

void HotelRoom::DisplayRoom()
{
cout << setprecision(2)
     << setiosflags(ios::fixed)
     << setiosflags(ios::showpoint);
cout << endl << "The following is pertinent data relating to the room:\n"
     << "Guest Name:        " << guest << endl
     << "Room Number:       " << roomNumber << endl
     << "Room Capacity:     " << GetCapacity() << endl
     << "Current Occupants: " << GetStatus() << endl
     << "Room Rate:         $" << GetRate() << endl;
}


int main()
{
int numOfGuests;
char roomNum[4]; 
char buffer[81];    //Buffer to store guest's name
int roomCap;
double roomRt;
bool badInput = true;
cout << endl << "Please enter the 3-digit room number: ";
do {        //loop to check user input
    badInput = false;   
    for(int x = 0; x < 3; x++)
    {
        cin >> roomNum[x];
        if(!isdigit(roomNum[x]))        //check all chars entered are digits
        {
            badInput = true;
        }
    }
    char x = cin.get();
    if(x != '\n')       //check that only 3 chars were entered
    {
        badInput = true;
    }
    if(badInput)
    {
        cout << endl << "You did not enter a valid room number. Please try again: ";
    }
} while(badInput);
for(;;)     //Infinite loop broken when correct input obtained
{
    cout << "Please enter the room capacity: ";
    if(cin >> roomCap) {
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}
for(;;)     //Infinite loop broken when correct input obtained
{
    cout << "Please enter the nightly room rate: ";
    if(cin >> roomRt) {
        break;
    } else {
        cout << "Please enter a valid rate" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}
cin.get();      //Dump the trailing return character
cout << "Please enter guest name: ";
cin.getline(buffer, 81);
HotelRoom room1(roomNum, buffer, roomCap, roomRt);
for (;;) {      //Infinite loop broken when correct input obtained
cout << "Please enter the number of guests for room #";
room1.DisplayNumber();
cout << ": ";
    if (cin >> numOfGuests) {
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}
room1.ChangeStatus(numOfGuests);
room1.DisplayRoom();
cout << endl << "The following shows after the guests have checked out." << endl;
room1.ChangeStatus(0);
room1.DisplayRoom();
room1.ChangeRate(175.0);
for (;;) {      //Infinite loop broken when correct input obtained
cout << "Please enter the number of guests for room #";
room1.DisplayNumber();
cout << ": ";
    if (cin >> numOfGuests) {
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}
room1.ChangeStatus(numOfGuests);
room1.DisplayRoom();
return 0;
}

更新:

我添加了cout语句,以查看程序中出现问题的位置,它肯定是在HotelRoom构造函数中的strcpy()语句中。这是构造函数,以下是我收到的输出

HotelRoom::HotelRoom(char room[], char guestName[], int capacity, double rate)
{
cout << endl << "Attempting 1st strcpy...";
strcpy_s(roomNumber, room);     //Compiles fine with strcpy on Linux, but MS is making me use strcpy_s to compile
cout << endl << "1st strcpy successful!";
guestName = new char[strlen(guestName) + 1];
cout << endl << "Attempting 2nd strcpy...";
strcpy_s(guest, guestName);     //Same as above
cout << endl << "2nd strcpy successful!";
roomCapacity     =  capacity;
currentOccupants = 0;
roomRate         = rate;
}

cout output

4 个答案:

答案 0 :(得分:1)

我想你可能需要再看一遍:

guestName = new char[strlen(guestName) + 1];
cout << endl << "Attempting 2nd strcpy...";
strcpy_s(guest, guestName);     //Same as above

我很确定,因为guestName[]是一个参数,你的意图是不要在函数范围内丢失该指针,用新分配的非终止指针替换它,然后继续复制未初始化的内存到您的成员变量。

也许你想要这个:

strcpy_s(guest, guestName);

此外,guestchar[81]类型的成员变量。除非您希望堆管理器再次抛出那个讨厌的对话框,否则您可能希望避免在类析构函数中执行此操作:

delete [] guest;

正在删除非堆内存并且全部但保证使堆管理器发呕。

答案 1 :(得分:0)

您定义了char buffer[81],但是您尝试阅读除cin.getline(buffer, 81)之外的81个字符\0。因此,您需要将之前的版本更改为char buffer[82]或更高版本为cin.getline(buffer, 80)

如果您使用C ++,为什么不使用string

答案 2 :(得分:0)

MS要求您使用_s函数的原因是为了保护您的代码免受当前显示的代码等缓冲区溢出的影响。查看this link了解详情。

你有一个81个字符的字符串。您新增了一个大小为+ 1的新字符串(您将丢失数据),现在是82个字符。当您尝试将缓冲区复制到长度为81个字符的guest虚拟机时,会出现断言。

考虑使用std :: string并停止分配/释放字符串,在你的情况下没用。

答案 3 :(得分:0)

如果你不使用strcpy_s,你需要在从指针复制到缓冲区之前自行检查边界。

此外,您不应该在guest上调用删除。删除用于释放使用new分配的内存。