【问题标题】:c++ program successfully build, No output, only show stack tracec++程序成功构建,没有输出,只显示堆栈跟踪
【发布时间】:2011-08-14 00:35:18
【问题描述】:

成功构建,但 Netbeans Run 输出堆栈跟踪

堆栈跟踪:

Frame     Function  Args
0022C694  7570EFA3  (00000108, 0000EA60, 00000000, 0022C7B8)
..............
End of stack trace

我正在逐行读取文件并使用 C++ 类概念检查它们是否有元音。

我已经测试了在不使用 C++ 类的情况下逐行读取文件并成功逐行写入文件。

请帮助指出我应该在哪里更改我的代码。我猜是内存管理问题。

非常感谢!

#include <cstdlib>
#include<fstream>
#include <iostream>

using namespace std;

class Password{
    private:
         char *pwd;
    public:
        Password(const char*pwd){
            setPassword(pwd);
        }
        ~Password(){
            delete []pwd;
        }
        void setPassword(const char *pwd){
            delete []this->pwd;
            if(pwd!=NULL){
                this->pwd=new char[strlen(pwd)+1];
                strcpy(this->pwd,pwd);
            }else{
                 this->pwd=NULL;
                }
        }
        char *getPassword(){
            return this->pwd;
        }
        bool containsVowel(){
            int i,counter=0;
            for(i=0;i<strlen(this->pwd);i++){
            if(this->pwd[i]== 'a' || 'e' || 'i' || 'o' || 'u' )
                counter++;
             }
            if (counter>0)
                return true;
            return false;
      }
};

int main(int argc, char** argv) {
    ifstream infile("C:/Users/user/Desktop/say.in"); 
    ofstream outfile("C:/Users/user/Desktop/say.out");
    string str; 
    while (getline(infile,str)){
       const char *pwd=str.c_str();
       Password pwdObj(pwd);
       if (pwdObj.containsVowel()==true){
    outfile<<"<"<<str<<"> is accpetable\r\n";
    }

    }
    infile.close();
    outfile.close();
    return 0;
}

【问题讨论】:

  • 您几乎可以肯定这里有内存管理问题。你 delete 销毁,但不 new (甚至初始化你的指针到 NULL!)在构造上,并且没有复制构造函数/op=。阅读有关 RAII 和三法则的信息。 std::string 有什么问题吗?

标签: c++ oop memory-management iostream


【解决方案1】:

有几件事。第一个是Password的pwd成员没有初始化,这可能会导致setPassword(...)第一次调用失败。您可以像这样在构造函数中初始化(参数重命名以避免混淆):

    Password(const char *apwd) : pwd(0) {
        setPassword(apwd);
    }

第二个问题是containsVowel 在你发布的时候已经很糟糕了。变量i 也没有初始化,我猜应该有一个循环——看起来它被省略了。 Delan 在回复中提到的比较也存在问题。

您还可以考虑将pwd 成员设为std::string。无论是在内存管理方面,还是在查找元音方面,这都会让您的生活更轻松 --- 我认为您可以使用 str.find_first_of(...) 来查找元音,而无需自己遍历所有字符。

【讨论】:

  • 密码(const char *pwd){ this->pwd=NULL;设置密码(密码); } 问题已解决,非常感谢!
  • 您可以通过在所有地方删除this-&gt; 来避免很多视觉混乱......并将pwd 初始化为零!
【解决方案2】:
if(this->pwd[i]== 'a' || 'e' || 'i' || 'o' || 'u' )

应该是

if(this->pwd[i]== 'a' || this->pwd[i]== 'e' || this->pwd[i]== 'i' || this->pwd[i]== 'o' || this->pwd[i]== 'u' )

【讨论】:

  • 不是真的,在尝试了你的建议后,smae问题仍然存在
  • 这只是您的代码的一个问题。可能还有其他人。
  • 这不是问题的答案,但肯定是一个有效的观察结果,并且必须在代码中修复。
【解决方案3】:

如果你这样做:

        delete []this->pwd;
        if(pwd!=NULL){
            this->pwd=new char[strlen(pwd)+1];

如果 this->pwd 为 NULL 会发生什么?

【讨论】:

    猜你喜欢
    • 2022-10-15
    • 2013-09-20
    • 2011-08-12
    • 1970-01-01
    • 2015-09-11
    • 2011-10-18
    • 2010-10-16
    相关资源
    最近更新 更多