-3

I am trying to create a segmented tree,

Here is my struct for the node of tree:

struct Node{
    int x1, x2; // x coordinates
    int y1, y2; // y coordinates
    Node * v1;
    Node * v2;
    Node * v3;
    Node * v4;
    bool oBo; //check if 1 by 1 
    bool O;
    bool F;
    int dimens;
    Node(int myx1, int myx2, int myy1, int myy2){
        this->x1 = myx1;
        this->x2 = myx2;
        this->y1 = myy1;
        this->y2 = myy2;
        this->dimens = abs(x2 - x1);
        if (dimens == 1)
        {
            this->oBo = true;
        }
        else
            this->oBo = false;

        this->O = false;
        this->F = false;

        this->v1 = NULL;
        this->v2 = NULL;
        this->v3 = NULL;
        this->v4 = NULL;
    }
};

This is my constructor for the Map

MapTree::MapTree(int iSize)
{
this->size = iSize;
root = new Node(0, size, 0, size);
segment(root);
}

and I am using the this segment function to make sub-segments of the root and then this is function is called recursively on the sub-nodes of root and so on. I get a bad memory alloc on the second segment. i.e when dimens = 2 and I have no idea why this is happening. I tried to fix it by changing the values and size but visual studio is not providing any clear error except bad memory alloc at certain memory location.

here is the segment function:

 void MapTree::segment(Node * node)
{
while (node->oBo != true)
{
    int dimension = node->dimens;
    node->v1 = new Node(0, dimension/2, 0 , dimension/2);
    node->v2 = new Node(dimension/ 2, dimension, 0, dimension/ 2);
    node->v3 = new Node(0, dimension / 2  , dimension / 2, dimension);
    node->v4 = new Node(dimension / 2, dimension, dimension / 2, dimension);

    segment(node->v1);
    segment(node->v2);
    segment(node->v3);
    segment(node->v4);
}

and last but not the least the size given for the tree is always the power of 2 so the segments are always going to end up being the size of one by one

OmG
  • 18,337
  • 10
  • 57
  • 90
Astronautilus
  • 83
  • 1
  • 9
  • The right tool to solve such problems is to use your debugger, but not to ask at Stack Overflow before you did so, and tell us all your observations you made when inspecting your code stepping through line by line. – πάντα ῥεῖ Aug 13 '16 at 20:52
  • TL;DR; You're probably trying to allocate some memory using an uninitialized varible. – πάντα ῥεῖ Aug 13 '16 at 20:53

1 Answers1

0

Never mind, I figured out what was wrong, I think I did not worded my question here correctly. but after some debugging I found the error, the loop was being called again again from the same position and hence infinite memory allocation. since root node->oBo will never be true hence infinite loop and bad memory alloc.

Astronautilus
  • 83
  • 1
  • 9