Tree with multiple nodes + memory leak

I am trying to implement a search algorithm,it needs a tree with four(NOTE n=4) nodes.Is the struct declaration correct for array of structure pointers??You see the main idea is start with the 'cur' node.Then take a new 'temp' node. Copy the contents of 'cur->state' into 'temp->state' then perform the 'res' operation.The result of which is stored in the 'cur->action[i]' node for every 'n' iteration.I am getting a memory leak ,I can only do one iteration.The program terminates at the 'temp' declaration during the second iteration.Please help me am I missing something??I have allocated and freed 'temp' then why the memory leak??Please ignore the other parts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  
 void srch(void *states,int nstates,int *actions,const int n,void (*res)(void *,int),unsigned long int (*heuc)(void *),bool (*gl)(void *))
 {
    typedef  struct tree
      {
             void *state;
              tree *action[4];
      };
      tree *cur=new tree;
      cur->state=states;
  
      for(int i=0;i<n;i++)
      {
         cur->action[i]=NULL;     
              
      }
      
      while(!(*gl)(cur->state))
     {
         int ph=0,max=0;
                              
         for(int i=0;i<n;i++)
         {
           
           tree *temp=new tree;
           memcpy( temp->state,cur->state,sizeof(cur->state)*nstates);

           for(int k=0;k<n;k++)
             temp->action[k]=NULL;

           (*res)(temp->state,actions[i]);
           cur->action[i]=temp;
            delete[] temp;
         }
        
        cur= cur->action[max];                    
     }          
      delete[] cur;
      
 }      
              
Last edited on
http://www.eelis.net/iso-c++/testcase.xhtml

$ valgrind --leak-check=full ./a.out
That site is not loading and I don't know how to use it.Can u tell the problem with my code.I am sure I must be making a very obvious mistake.Is the format of the struct and the way it is called correct??I am missing something here...
first fix your indentation.
then, provide enough code to reproduce your problem.

> I must be making a very obvious mistake.
T *foo = new T;

new and delete[]
`memcpy()'

those smell bad.
Last edited on
Fixed indentation...Should I not use 'memcpy()' when using 'new'??
What alternative would you suggest??
> What alternative would you suggest?
making `states' a container.
copy constructor
std::copy()


1
2
           tree *temp=new tree;
           memcpy( temp->state,cur->state,sizeof(cur->state)*nstates);
¿is `temp->state' initialized?

1
2
           cur->action[i]=temp;
            delete[] temp;
first, it should be delete temp;, as you had allocated with new
second, note how those two line may be swapped without altering the meaning. ¿why are you storing an invalid pointer?
Topic archived. No new replies allowed.