试图初始化矩阵C 时的不良同种
Bad alloc when trying to initialize matrix C++
我试图将2D矩阵放入AVL树中。但是,我一直在抛出bad_alloc实例后不断获得"终止"。错误,然后程序崩溃。这是我的代码:
struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
int **M;
};
struct Node* newNode(int key)
{
struct Node* node = new struct Node;
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
if(key == (0 % 3)){
cout <<"Matrix" <<endl;
int n = pow(2, 20);
node->M = new int*[n];
for (int i = 0; i < n; i++){
node->M[i] = new int[n];
}
// freemat(node, n);
}
else if (key == (1 % 3)){
cout <<"Matrix" <<endl;
int n = pow(2, 19) + pow(2, 18);
node->M = new int*[n];
for (int i = 0; i < n; i++){
node->M[i] = new int[n];
}
// freemat(node, n);
}
else if(key == (2 % 3)){
cout <<"Matrix" <<endl;
int n = pow(2, 18) + pow(2, 17);
node->M = new int*[n];
for (int i = 0; i < n; i++){
node->M[i] = new int[n];
}
// freemat(node, n);
}
return(node);
}
freemat是我创建的一个函数来释放矩阵,因为我认为这是问题所在,但是即使在"释放"矩阵之后,我仍然遇到了问题。
int freemat(struct Node *N, int n){
for(int i = 0; i < n; ++i)
delete [] N->M[i];
delete [] N->M;
}
程序编译,打印出"矩阵"一词,然后在下面打印错误。
bad_alloc通常来自您的内存。您是否尝试过在GDB下运行此操作以查看此操作?2^20 * 2^20 * sizeof(int(大约是8 tb!
另外,一些未经请求的评论(随时无视(:看起来您是根据freemat函数以及如何初始化结构来从C背景来的。与C的malloc方法不同,如果无法分配请求的内存,则返回null,C 的新功能会抛出bad_alloc。
最后,您的检查(键==(1%3((没有意义。1%3总是一个,因此除非您打算检查(键== 1(,否则您可能想要(键%3 == 1(。
这不是问题的答案 - 对不起,但是要发表评论太久。
摆脱所有分支的一种方法
static const powers[] =
{
1 << 20,
1 << 19 + 1 << 18
1 << 18
};
std::cout << "Matrixn";
int n = powers[key % sizeof(powers)];
node->M = new int*[n];
for (int i = 0; i < n; ++i)
node->M[i] = new int[n];
这仍然会分配大量的内存,并且仍然会破坏您的计算机并捕捉火焰。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 试图初始化矩阵C 时的不良同种
- C - 空数对象的初始化发送不良访问错误
- 初始化不正确的价值不良样式后,正在抛出异常
- C 指针初始化的不良初始化可能是什么后果