Pregunta

I am making a Red Black Tree implementation and am currently testing the 'dump' function.

This function is an in-order traversal of the tree which saves each element in the tree into a dynamic array and returns the pointer to that array.

Upon debugging I've found the function works properly and the array contains the elements it should. But when the test function tries to 'cout' the first element of the array, I get

Assignment4.exe has triggered a breakpoint.

followed by malloc.c opening to this:

__forceinline void * __cdecl _heap_alloc (size_t size)

{

    if (_crtheap == 0) {
        _FF_MSGBANNER();    /* write run-time error banner */

        _NMSG_WRITE(_RT_CRT_NOTINIT);  /* write message */
        __crtExitProcess(255);  /* normally _exit(255) */
    }

→    return HeapAlloc(_crtheap, 0, size ? size : 1);
}

So here is the code that may be the culprit:

The Functions:

int* /*T*/ RedBlackTree::dump(int& number)
{
    int* /*T*/ arr = new int(n);
    number = 0;

    inOrder(root, arr, number);

    return arr; //returns pointer to entire tree in ascending order
}

void RedBlackTree::inOrder(Node* nd, int* /*T*/ arr, int& num)
{
    if(nd != NULL)
    {
        inOrder(nd->left, arr, num);
        arr[num] = nd->data;
        num++;
        inOrder(nd->right, arr, num);
    }

}

And the Test Function:

int main()
{
    RedBlackTree tree;

    //insert test
    tree.insert(15);
    tree.insert(20);
    tree.insert(20);
    tree.insert(21);
    tree.insert(48);
    tree.insert(18);
    tree.insert(1);
    tree.insert(7);
    tree.insert(25);

    //dump test
    int* arr = new int(tree.size());
    int n = 0;
    arr = tree.dump(n);

    for(int i = 0; i < n; i++)
    {
→       cout << arr[i] << " ";
    }

    return 0;
}

I put an arrow on the line that triggered the error.

I checked with the debugger and a quick watch that each element from i = 0 to i = 8 does exist in the array just before that line is executed.

Thank you all for your help!

¿Fue útil?

Solución

int* arr = new int(tree.size());
int n = 0;
arr = tree.dump(n);

Here is the problem.

You first allocate an array to arr with tree.size(), which looks fine. However, inside tree.dump(n) you have allocated another array with size n and return back to arr. At this point, arr is actually an array with size n which is 0 in your case. Accessing this array should be illegal.

On the other hand, if you write it this way, it will cause Memory Leak, i.e. the original memory pointed by arr will be lost deal to another memory address assignment on arr with tree.dump(n).

And remember to delete what you have new, this is a good programming practice.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top