【发布时间】:2021-05-15 23:41:35
【问题描述】:
我创建了一个 SLL,其中填充了大小为 [2] 的数组对象。目标是使用 SLL 保存用户名和密码列表。我在文件中有一个名称列表。我能够读取列表并将姓氏写入新文件。但是,当我将 SLL 中的对象全部设为数组并尝试使用用户名保存相应的密码时,在尝试访问数组时出现错误的分配错误。
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
这是我的 main.cpp
LinkedList* listOfNames = new LinkedList[2]();
void readFile(std::string newFile){
ifstream inFile(newFile);
std::string firstWord;
while(inFile >> firstWord)
{
listOfNames[0].InsertAtHead(firstWord);
listOfNames[1].InsertAtHead("password");
inFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
inFile.close();
}
void writeFile(std::string outFilename)
{
Node *temp = new Node[2];
temp = listOfNames->getHead();
ofstream outFile(outFilename);
while(temp != NULL)
{
outFile << temp[0].GetValue() << " " << temp[1].GetValue() << std::endl;
temp = temp->GetNext();
}
outFile.close();
}
如果我注释掉我尝试访问数组中的 2 个项目的行,那么它运行良好。
outFile << temp[0].GetValue() << " " << temp[1].GetValue() << std::endl
我知道我有内存分配问题,但我不知道如何解决。
下面是我的 LinkedList.cpp 和 Node.cpp。它们排在最后是因为它们可能是多余的。
Node::Node()
{
this->value = "";
this->next = nullptr;
}
Node::Node(std::string value)
{
this->value = value;
this->next = nullptr;
}
std::string Node::GetValue()
{
return this->value;
}
void Node::SetNext(Node* next)
{
this->next = next;
}
Node* Node::GetNext()
{
return this->next;
}
LinkedList::LinkedList()
{
this->head = nullptr;
this->tail = nullptr;
this->size = 0;
}
void LinkedList::InsertAtHead(std::string value)
{
Node* newNode = new Node(value);
newNode->SetNext(this->head);
this->head = newNode;
if(this->tail == nullptr)
{
this->tail = newNode;
}
this->size++;
}
void LinkedList::Print()
{
Node* currentNode = this->head;
while(currentNode != nullptr)
{
std::cout << currentNode->GetValue() << std::endl;
currentNode = currentNode->GetNext();
}
}
Node* LinkedList::getHead()
{
return this-> head;
}
节点.hpp
class Node
{
private:
std::string value;
Node* next;
public:
Node();
Node(std::string value);
std::string GetValue();
void SetNext(Node* next);
Node* GetNext();
};
linked_list.hpp
class LinkedList
{
private:
Node* head;
Node* tail;
int size;
public:
LinkedList();
void InsertAtHead(std::string value);
void Print();
Node* getHead();
};
#endif
【问题讨论】:
-
似乎是学习如何使用调试器的好时机。
-
请在这里也提供节点声明!乍一看:这是一个非常有问题的设计: Node *temp = new Node[2];然后进一步隐式假设类型适合迭代......将纯单对象语义与数组语义混合。也许这也是你崩溃的原因。
-
@Secundi 我添加了我的声明。你能帮我找到更好的解决方案吗?
标签: c++ arrays memory-management dynamic-memory-allocation singly-linked-list