【发布时间】:2011-08-05 23:13:38
【问题描述】:
我有下面的代码解析一个文本文件并索引单词和行:
bool Database::addFromFileToListAndIndex(string path, BSTIndex* & index, list<Line *> & myList)
{
bool result = false;
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
Line * ln;
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
ln = new Line(line, path, lineNumber);
if(ln->getLine() != "")
{
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
}
result = true;
}
return result;
}
在我给它一个巨大的文本文件之前,我的代码可以完美且相当快速地运行。然后我从 Visual Studio 收到堆栈溢出错误。当我切换到“发布”配置时,代码运行顺利。我的代码有问题还是在运行“调试”配置时存在某种限制?我是否试图在一个功能中做太多事情?如果是这样,我该如何分解它以使其在调试时不会崩溃?
编辑 根据请求,我的 addWord 实现;
void BSTIndex::addWord(BSTIndexNode *& pCurrentRoot, string word, Line * pLine)
{
if(pCurrentRoot == NULL) //BST is empty
{
BSTIndexNode * nodeToAdd = new BSTIndexNode();
nodeToAdd->word = word;
nodeToAdd->pData = pLine;
pCurrentRoot = nodeToAdd;
return;
}
//BST not empty
if (word < (pCurrentRoot->word)) //Go left
{
addWord(pCurrentRoot->pLeft, word, pLine);
}
else //Go right
{
addWord(pCurrentRoot->pRight, word, pLine);
}
}
还有lineParser:
vector<string> Database::lineParser(Line * ln) //Parses a line and returns a vector of the words it contains
{
vector<string> result;
string word;
string line = ln->getLine();
//Regular Expression, matches anything that is not a letter, number, whitespace, or apostrophe
tr1::regex regEx("[^A-Za-z0-9\\s\\']");
//Using regEx above, replaces all non matching characters with nothing, essentially removing them.
line = tr1::regex_replace(line, regEx, std::string(""));
istringstream iss(line);
while(iss >> word)
{
word = getLowercaseWord(word);
result.push_back(word);
}
return result;
}
【问题讨论】:
-
这与问题无关,但似乎有空行泄漏。该代码创建了一个
new Line(...)对象,如果该行为空,则似乎永远不会删除它。 -
@Mark 谢谢,你是对的,现在已经修复了。
-
@sarnold 不,这不是堆栈溢出的原因。他只是指出这一点,这就是他评论而不是回答的原因。
-
@Pete:你的巨大文本文件有多大?如果您只是在 Release 中可用地址空间的限制范围内,因为 Debug 可能会在内存中添加一些东西(堆栈保护,...),您可能会超出限制然后崩溃。
-
您也可能正在破坏您的堆栈,并且只能在调试中检测到它,这要归功于堆栈防护(不确定 VS 是如何处理的)。如果你能用 valgrind 之类的东西来检查它会很酷。
标签: c++ stack-overflow