Passing pointers to allocate memory

closed account (j6pf92yv)
Hi guys,

Really basic question, but I'm having problems as I'm trying to build my first linked list. My problem occurs when i want to allocate memory for a new node within my template function.

Before I tried to tidy up my code i simply used the form:

1
2
3
4
T * pNode = NULL;     
pNode = new T;
...
delete pNode;


I trying to make the code more secure by hiding the memory allocation. I want to call a member function of myList to create the new node. Can you tell me where I'm going wrong with my member functions. Right now i get nasty heap corruption(?) when i try to delete after using version 1. Version 2 meanwhile won't pass out the correct address.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
T * pNode = NULL;

Version 1:

   Node =&(myList.GenerateNode(pNode));

   T GenerateNode(T * NewNode)	
   { 
     NewNode = new T;
     return *NewNode;
   };

Version 2:

   void GenerateNode(T *NewNode)
   {
      T * test = new T;
      temp = test;
   }

...
delete pNode;


I guess reading this question will have taken you longer than it took you to solve my problem. Thanks in advance to anyone who can spare a moment to help me out and possibly explain what schoolboy error i've made
Last edited on
You want a reference to a pointer...
1
2
3
4
5
T GenerateNode(T*& newNode)
{
   newNode = new T;
   return *newNode;
}


Now you are modifying the original pointer rather than a copy of the pointer.

Also the following is not valid:
Node =&(myList.GenerateNode(pNode))
because you are taking the address (Using &) of a temporary object.

The following is probably closer to what you want...
1
2
3
4
5
6
T* GenerateNode()
{
   return new T;
}

pNode = GenerateNode();


or

1
2
3
4
5
void GenerateNode(T*& newNode)
{
   newNode = new T;
}
GenerateNode(pNode);
Last edited on
Topic archived. No new replies allowed.