Home > Software engineering >  Access violation reading location 0xFDFDFE01
Access violation reading location 0xFDFDFE01

Time:11-22

This is the entire code, i use no header files this code must input a tree and then write out its high, the problem is in the function High() in the line if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {, it says : Access violation reading location 0xFDFDFE01.

#include<iostream>
using namespace std;

int** InputTree() {
    int n, nd, father;
    int child;
    char dir;
    std::cin >> n;
    int** tree = new int* [n];
    for (int i = 0; i < n; i  ) {
        std::cin >> nd;
        tree[i] = new int[3];
        tree[i][0] = nd;
        tree[i][1] = -1;
        tree[i][2] = -1;
    }

    for (int i = 0; i < n - 1; i  ) {
        std::cin >> father >> child >> dir;
        if (dir == 'L')
            tree[father][1] = child;
        else
            tree[father][2] = child;
    }
    return tree;
}

int High(int** tree, int headIndex) {
    if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {
        return 1;
    }
    int high1 = High(tree, tree[headIndex][1]);
    int high2 = High(tree, tree[headIndex][2]);
    return (high1 > high2 ? high1 : high2);
}

int main(){
    int** t = InputTree();
    cout << High(t, 0);
    system("pause>NULL");
    return 0;
}

CodePudding user response:

A recursive call to High can be called with headIndex equal to -1. Your recursion only stops when both child nodes are -1, but if one of them is -1 and the other points to another node, you'll make a recursive call and dereference an out-of-bounds index.

One way to fix this is to check each node before making the recursive call, for example:

int high1 = tree[headIndex][1] == -1 ? 1 : High(tree, tree[headIndex][1]);
  • Related