troubles with VC++6

Hi All,
I have the following code in VC++:

In TestView.h :

/***********************************/
......
.....
typedef struct t_test
{
int a, b;
struct t_test *next;
} Object;

class CTestView : public CView
{
public :
Object *Obj;
Object Make(int a1, int b1);
void Read();
void foo();
int N;
.......
}


In TestView.cpp the functions are as follows :

Object CTestView::Make(int a1, int b1)
{
Object *tmp;

tmp = (Object *)malloc(sizeof(Object));
tmp->a = a1;
tmp->b = b1;
return(*tmp);
}

void CTestView::Read()
{
Object *new_o;

new_o = &Make(1, 2);
new_o->next = Obj;
Obj = new_o;
++N;

new_o = &Make(3, 4);
new_o->next = Obj;
Obj = new_o;
++N;
}

void CTestView::OnLButtonDown(.....) // or any other function
}
Read();
foo();
}

/************************************/

That is the essence of the code. Variable N is zeroed and Obj is NULL (Obj = NULL) in the constructor. My problem is :

In Read() the values for Obj are correctly assigned(a=1, b=2, and 'next' is 3, 4). But after the function Read() is left and enters in foo() (OnLButtonDown) the values of Obj are completely change (other values for a and b and next is not accessible).

By the way, I know the stuff with malloc()/free and new/delete :-)

What's wrong ? How can you correct ?

Thank you. The Curious 08
1
2
3
4
5
6
7
8
9
Object CTestView::Make(int a1, int b1)
{
Object *tmp;

tmp = (Object *)malloc(sizeof(Object));
tmp->a = a1;
tmp->b = b1;
return(*tmp);
}


You are better off returning the ptr (or reference) to the newly created object:

1
2
3
4
5
6
7
8
9
10
Object * CTestView::Make(int a1, int b1)
{
  Object *tmp;

  tmp = (Object *)malloc(sizeof(Object));
  tmp->a = a1;
  tmp->b = b1;
  tmp->next = NULL;
  return tmp;
}


then in your read function you need clean that up cause it makes no sense. It easier to have two pointers, one pointing to first element and one on the last.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Object *First = NULL, *Last = NULL; // prefer use names that are descriptive
...

void CTestView::Read()
{
   Object *new_o = Make(1,2);  // created new object

   if ( First == NULL || Last == NULL ) // check if this is the first object
   {
      First = Last = new_o;
   }  
   else  // Start already pointing to first element, End to last
   {
      Last->next = new_o; // add new object to list
      Last = new_o; // new last element
   }
   ++N;

   new_o = Make(3, 4); // create next object
   Last->next = new_o; // let last element point to newly created object
   Last = new_o; // this our new last element
   ++N;
}


If you instead use new/delete you can skip the lines "next=NULL" since you could initialize its members in the constructor.
Last edited on
Topic archived. No new replies allowed.