Memory help

Hi, well , I have a function which returns a pointer. Lets call it function 1.
So, inside another function(function 2) I call a 3rd function, using function1 as one of the paramaters. But the problem is, once that I pass the function2 into function 3 I don't want the allocated memory from function2 anymore. How to delete it?

So, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pointer* function1()//returns a pointer
{

 return pointer;
}
void function2()//uses this pointer to call function 3
{

function3(*function1());
//I need to delete the pointer when it returns here, how do I do it?
//If I do delete[]function1(); will that run the function again and create //ANOTHER pointer and delete it, thus leaving the original pointer intact?

}
void function3(ref&)//uses the pointer to do stuff
{
//do stuff
//**Is it possible to delete a pointer using the reference?**//
}


I hope I explain nicely...

Last edited on
Is it possible to delete a pointer using the reference?

No you can only delete that memory using the pointer
im not sure if i get this right.
but why dont you save the pointer function1 gives you in a variable?
1
2
3
4
5
6
void function2()//uses this pointer to call function 3
{
    type *ptr = function1();
    function3(ptr);
    delete ptr; //or delete[] if the pointer memory was allocated with new[]
}


Will that not just make the new pointer, point to the same place as function1(), therefore the function1() pointer will still be hanging about?
yeah, my solution above wasnt working as i thought it would. you were right there.
but you could try std::auto_ptr. it takes care of deleting the allocated memory for you.
if you want to use some STL stuff, auto_ptr does not work... (maybe you want to check out boost::shared_ptr, www.boost.org)

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
#include <iostream>
#include <memory>
using std::cin;
using std::cout;
using std::endl;

std::auto_ptr<char> function1()
{
	std::auto_ptr<char> ptr(new char);
	cout << &ptr << "- in function1" << endl;
	return ptr;
}

void function3(std::auto_ptr<char> &ptr)
{
	cout << &ptr << "- in function3" << endl;
}

void function2()
{
	std::auto_ptr<char> ptr(function1());
	cout << &ptr << "- in function2" << endl;
	function3(ptr);
	cout << &ptr << "- in function2" << endl;
}


int main(){
	function2();
	return 0;
}


if you run the program it will print the adress of each auto_ptr. always the same, and when function2 is left, the pointer will be deleted automaticly. (oh i hope im not mixing stuff up here... :-/ )
Last edited on
Topic archived. No new replies allowed.