C++大型2D数组访问冲突

C++ large 2D Array access violation

本文关键字:访问冲突 数组 2D 大型 C++      更新时间:2023-10-16

所以我创建了一个程序,用于查找最佳二进制搜索树,当数据集大约为100时,它非常有效,但当我尝试使用大于1000的数据集时,当weight[I][I]=frequency[I]时,我会遇到访问违规;在computeOBST函数内部调用。我不确定这个数据集是很大还是什么。我被卡住了,不确定还能做些什么来尝试任何帮助都会很好。

int* keys = new int[numKeys];                   
int* keyLevel = new int[numKeys];               
int* frequency = new int[numKeys];              
int** weight = new int*[numKeys+2];             
int** cost = new int*[numKeys];                 
int** root = new int*[numKeys];                 
void allocateArraySpace(int n){
    int i;
    // Allocate space for the 2-dim'l cost array
    for (i = 0; i < numKeys + 2; i++) {
        cost[i] = new int[numKeys + 2];
    }
    for (i = 0; i < numKeys + 1; i++) {
        keyLevel[i] = numKeys + 1;
    }
    // Allocate space for the 2-dim'l root array
    for (i = 0; i < numKeys + 1; i++) {
        root[i] = new int[numKeys + 1];
    }
     //Allocate space for the 2-dim'l weight array
    for (i = 0; i <= numKeys + 2; i++) {
        weight[i] = new int[numKeys + 2];
    }
}
void computeOBST(int n) {
    numKeys = n;
    int i, j, k, h, m;
    allocateArraySpace(numKeys);
    //creating weight matrix
    for (int i = 1; i <= numKeys + 1; i++)
    {
        weight[i][i] = frequency[i];
        for (j = i + 1; j <= numKeys; j++)
            weight[i][j] = weight[i][j - 1] + frequency[j];
    }
    //
    for (i = 1; i <= numKeys; i++)
        for (j = i + 1; j <= numKeys + 1; j++)
            cost[i][j] = INT_MAX;
    //
    for (i = 1; i <= numKeys + 1; i++)
        cost[i][i - 1] = 0;
    //
    for (i = 1; i <= numKeys; i++) {
        cost[i][i] = weight[i][i];
        root[i][i] = i;
    }

cost的大小只有numKeys,但在allocateArraySpace中的循环中,您访问它的numKeys+2元素吗?其他阵列也存在类似的问题。

请记住,C++中的数组是基于0的,所以如果执行cost = new int *[numKeys],那么cost[numKeys-1]是可以的,但cost[numKeys]cost[numKeys+1]是越界的。

int* frequency = new int[numKeys]

然后

for (int i = 1; i <= numKeys + 1; i++) { weight[i][i] = frequency[i]; ...

你会出界的未定义的行为。碰巧,小值的UB不会导致分割错误,而numKeys的高值则会导致分割错误。

这只是一个例子,你在很多地方都有同样的错误。再次检查所有循环和数组边界,并设置正确的限制。

通常,当您跨越大小为numKeys的阵列时,您可以按以下方式扫描它(请记住,C阵列是基于零的):

for (int i = 0; i < numKeys; i++) // first index is 0, last is numKeys-1