passing pointers and memory leaks

Posted 20 January 2012 - 04:14 PM

Suppose that we have a class with a double pointer called element that is used in a method called operation. Operation does not change element and only uses it as an input. A double pointer is created in the main function and is assigned to the element property of an instance of the class.

I have two questions regarding the following code:
1. Is this a good practice? If not what is wrong with it?
2. Does the following code create a memory leak or dangling pointers? I am just deleting the double pointer created in the main function and set the element to NULL within the destructor of the class. (Since CLQ does not have the value for the size variable, I only set element = 0).

Re: passing pointers and memory leaks

Just because you can write memory leaks, doesn't mean you should. Your current code generates size+1 memory leaks. It's unclear how it could run without crashing.

Simply:

int *a = new int[10]; // allocated 10 ints to a
// do something
a = 0;
// congratulations, a has now lost all reference to what it was pointing to.
delete [] a; // this should segfault you. You deserve it.

It's also a profound OO fail. The class should contain all that nasty pointer stuff so the user needn't work about any possibility of a memory leak.
e.g.

Re: passing pointers and memory leaks

Posted 20 January 2012 - 06:08 PM

Ideally, you'd just put the 2d array in your class. You want to expose an easy-to-use client API. You don't want the client to handle the matrix, unless your class is a utility class, which would have mostly static methods, like in jjl's example. Here's an example. The client API is nice and easy to use: