C++ 新操作员未正确分配内存。
假设我的代码使用和节点数组创建一个单链表 每个节点都有保存数据的变量项和保存列表中下一个节点索引的变量next。最后一个节点在其下一个数据字段中具有-1以模拟nullptr。head保存列表中第一个节点的索引 由于某种原因,当我试图创建新内存时,程序抛出一个bad_alloc实例 在抛出“std::bad_alloc”实例后调用terminate 什么():std::坏的C++ 新操作员未正确分配内存。,c++,linked-list,dynamic-memory-allocation,C++,Linked List,Dynamic Memory Allocation,假设我的代码使用和节点数组创建一个单链表 每个节点都有保存数据的变量项和保存列表中下一个节点索引的变量next。最后一个节点在其下一个数据字段中具有-1以模拟nullptr。head保存列表中第一个节点的索引 由于某种原因,当我试图创建新内存时,程序抛出一个bad_alloc实例 在抛出“std::bad_alloc”实例后调用terminate 什么():std::坏的 #包括“ArrayList.h” #包括 使用名称空间std; ArrayList::ArrayList(char-ch){
#包括“ArrayList.h”
#包括
使用名称空间std;
ArrayList::ArrayList(char-ch){
数组=新节点[大小];
(数组[0])。项=ch;
(数组[0])。next=1;
自由=1;
水头=0;
}
bool ArrayList::cons(char-ch){
如果(此->已满()){
此->双数组();
}
(数组[free])。项=ch;
(数组[free])。下一个=头;
头部=自由;
自由++;
//难道没有多个新的。哪一个是问题?我不认为问题在于“新的”。问题在于您的cons和isFull函数。cons函数的值是一个一个地增加。在isFull中,您开始从头开始计数,因为head总是增加一个,所以count==Size是不可能的。请将每个分配包装在一个try catch块中,以查找异常的来源。在分配之前,还要查看请求的大小。@deviantfan t双数组中的一个在双数组中您有一个越界访问权限,因为计数将等于上一次迭代中的旧大小。
#include "ArrayList.h"
#include <iostream>
using namespace std;
ArrayList::ArrayList(char ch){
array = new Node[Size];
(array[0]).item = ch;
(array[0]).next = 1;
free = 1;
head = 0;
}
bool ArrayList::cons(char ch) {
if (this->isFull()){
this->doubleArray();
}
(array[free]).item = ch;
(array[free]).next = head;
head = free;
free++;
// cout << free << endl;
return true;
}
bool ArrayList::isFull() const{
int current = head;
int count =0;
while( (array[current]).next != -1 ){
count++;
current = (array[current]).next;
}
return (count == Size) ? true : false;
}
bool ArrayList::doubleArray() {
int oldSize = Size;
Size *=2;
Node* newArray = new Node[Size]; // problem occurs here, i think
int count =0;
while(oldSize >= count ){
(newArray[count]).item = (array[count]).item;
(newArray[count]).next = (array[count]).next;
count++;
}
free = count +1;
delete [] array;
array = newArray;
cout <<"free: "<< free << endl;
return true; // come up with thiss
}
void ArrayList::print() const{
if (head == -1) return;
int current = head;
cout << "[ ";
while( (array[current]).next != -1){
cout << (array[current]).item <<" ";
current = (array[current]).next;
}
cout << (array[current]).item <<"]";
return;
}
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <iostream>
using namespace std;
class Node{
public:
char item;
int next;
Node(){
next = -1;
}
Node(char input){
this->item = input;
next = -1;
}
};
class ArrayList{
public:
ArrayList(char ch);
int length() const;
void print() const;
private:
bool doubleArray();
bool isFull() const;
Node* array;
int Size = 5;
int head = -1;
int free = 0;
};
#endif
#include <iostream>
#include "ArrayList.h"
using namespace std;
int main(){
ArrayList list('1');
list.cons('2');
list.cons('3');
list.cons('4');
list.cons('5');
list.cons('6');
list.cons('7');
list.print();
//cout << list.length();
return 0;
}