试图初始化矩阵C 时的不良同种

Bad alloc when trying to initialize matrix C++

本文关键字:不良 初始化      更新时间:2023-10-16

我试图将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];

这仍然会分配大量的内存,并且仍然会破坏您的计算机并捕捉火焰。