打印字符串时出现运行时错误,即使它在函数中运行良好

Runtime error printing string, even though it works fine in a function

本文关键字:函数 运行 字符串 运行时错误 打印      更新时间:2023-10-16

处理一个简单的基于C++指针的堆栈程序。我正试图打印一个字符串,它是NameItem类的一部分,PointerStack类将其用作其项类型(请参阅代码)。每当我试图在程序的main()函数中打印字符串时,控制台就会重复打印胡言乱语和嘟嘟声。但是,当我调用PrintPointerStack函数时,没有任何错误,所有内容都按预期打印。

我尝试过更改类,重新排列代码,虽然我可以确定哪一行产生了错误,但我不知道为什么。我在这里完全迷路了,以前从未见过这样的事情,所以如果答案很简单,并在谷歌搜索中找到,我很抱歉,但我已经搜索了几个小时,只是不知道该搜索什么了。

代码如下:

#include <iostream>
#include <string>
#include <stack>
#include <cstddef>
#include <new>
using namespace std;
#include "NameItem.cpp"
#include "Stack.cpp"
#include "PointerStack.cpp"
void PrintPointerStack(PointerStack printer){
    NameItem temp;
    while(!printer.IsEmpty()){
        temp = printer.Top();
        printer.Pop();
        temp.Print();
    }
    cout << endl;
}
int main(){
    string initNames[] = {"Michael","Charlie","Susan","Alexa",
                          "Jason","Candice","Beatrice","Lois",
                          "Peter","Matthew"};
    int initNamesLen = 10;
    PointerStack PStacker, tempPStacker;
    NameItem filler;
    for(int i = 0; i < initNamesLen; i++){
        filler.Init(initNames[i]);
        PStacker.Push(filler);
    }
    cout << endl << "---------- Pointer-based Stack ----------" << endl << endl;
    PrintPointerStack(PStacker);
    cout << "Top: ";
    (PStacker.Top()).Print(); //This is where the program errors. I've tried creating a
                              //temp variable like in the function above, and I've
                              //tried accessing the string directly and printing it
                              //from main() using cout, which produce the same results.
                              //So the error is caused specifically by the cout <<
                              //string statement, when I try to use that statement
                              //within the bounds of the main function.  
    cout << endl;
    PrintPointerStack(PStacker);
    cout << endl << "Popped: ";
    (PStacker.Top()).Print();
    PStacker.Pop();
    (PStacker.Top()).Print();
    PStacker.Pop();
    cout << endl;
    PrintPointerStack(PStacker);
    cout << endl << "Pushed: Sammy Valerie" << endl;
    filler.Init("Sammy");
    PStacker.Push(filler);
    filler.Init("Valerie");
    PStacker.Push(filler);
    PrintPointerStack(PStacker);
    try{
        PStacker.Push(filler);
    }
    catch(FullStack){
        cout << endl << "Stack is full, name not pushed" << endl;
    }
    cout << endl << "Popped: ";
    while(!PStacker.IsEmpty()){
        filler = PStacker.Top();
        PStacker.Pop();
        filler.Print();
    }
    try{
        PStacker.Pop();
    }
    catch(EmptyStack){
        cout << endl << "Stack is empty, name not popped" << endl;
    }
    return 0;
}

PointerStack类

#include "PointerStack.h"
PointerStack::PointerStack(){
    top = NULL;
}
/*PointerStack::~PointerStack(){
    Node* temp;
    while(top != NULL){
        temp = top;
        top = top->next;
        delete temp;
    }
}*/
void PointerStack::Push(NameItem item){
    if(IsFull())
        throw FullStack();
    else{
        Node* location;
        location = new Node;
        location->data = item;
        location->next = top;
        top = location;
    }
}
void PointerStack::Pop(){
    if(IsEmpty())
        throw EmptyStack();
    else{
        Node* temp;
        temp = top;
        top = top->next;
        delete temp;
    }
}
NameItem PointerStack::Top(){
    if(IsEmpty())
        throw EmptyStack();
    else{
        return top->data;
    }
}
bool PointerStack::IsEmpty() const{
    return (top == NULL);
}
bool PointerStack::IsFull() const{
    Node* location;
    try{
        location = new Node;
        delete location;
        return false;
    }
    catch(std::bad_alloc& exception){
        return true;
    }
}

和NameItem类

#include <fstream>
#include "NameItem.h"
NameItem::NameItem()
{
    name = " ";
}
RelationType NameItem::ComparedTo(NameItem otherItem) const
{
    if (name < otherItem.name)
        return LESS;
    else if (name > otherItem.name)
        return GREATER;
    else 
        return EQUAL;
}
void NameItem::Init(string value)
{
    name = value;
}
void NameItem::Print() const
{
    cout << name << " ";
}

最后要注意的是,主程序中包含了更多用于测试Stack类的代码。我删除了代码,因为它与错误无关,程序仍然会崩溃,但它会立即崩溃,出现窗口错误框,而不是控制台的胡言乱语/嘟嘟声。不确定这是否相关。。。

问题有两个方面。

首先,清空PrintPointerStack()中的PStacker对象,然后尝试访问该空堆栈的顶部元素。这应该抛出一个EmptyStack。事实上,这种情况没有发生,这也表明了另一个问题(见下文)。

其次,giberish被打印(有时)表明您试图通过无效的对象/指针访问数据。事实上,因为您通过pass-by-value传递PrintPointerStack()的参数,所以会调用默认的复制构造函数来盲目复制top指针的值。然后继续删除对象,但原始PStacker中的top指针没有更改,因此现在无效。这就是你的问题。

要修复此问题,您需要通过指针/引用将参数传递给PrintPointerStack(),或者提供一个更适合执行深度复制的复制构造函数(而不是默认复制构造函数提供的浅复制)。