how to prevent memory leek

how would you prevent memory leek in this situation :

1
2
3
4
5
6
7
8
9

int * ReturnPointer2()
{
	int * ptr = new int(3);
	
	return ptr;
}

There isn't a memory leak, providing you do this:
int *answer = ReturnPointer2();

But if you do this, there is a leak (and there's not much you can do about it).
/*ignoring return result*/ReturnPointer2();

If you make use of things like this, scope is tracked for you.
http://www.cplusplus.com/reference/memory/unique_ptr/
Last edited on
Salem C was pretty low key in his answer; I think it's worth saying this a bit harder:

To avoid memory leaks, don't use new. Don't use delete. Don't do manual memory management. The order of preference is:

1) On the stack, not the heap.
2) If you MUST have it on the heap, create it with make_unique or make_shared, and use a unique_ptr or a shared_ptr to manage its lifetime.
3) If you really can't do that, go back and redesign your code so that you can.
4) When you've got enough experience and knowledge to know the cases when you really really must do it yourself, manually, you'll try really hard not to.
Last edited on
closed account (E0p9LyTq)
how would you prevent memory leak in this situation

1. By not using a Variable Length Array (VLAs).
2. By not using new, especially in a function.

I'd use one of the STL containers, such as a std::vector or std::array. Memory management is built in. When the container object goes out of scope, so does it's its used memory.
Topic archived. No new replies allowed.