0

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;
}
  • Likely an offset to 0xFDFDFDFD. Related: [https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations](https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations) – drescherjm Nov 21 '21 at 00:17
  • vote up my question plz – Moataz Craft Nov 21 '21 at 18:15

1 Answers1

1

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]);
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56