【发布时间】: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