Is this fine?
Not quite. There are a couple problems. One -- your troublesome use of free
-- we'll address in a moment. But first, your use of new[]
with delete
(non-[]
) invokes Undefined Behavior:
Here you are using new []
:
nEncodedBytes = new unsigned char[m_lLenCompressedBytes];
And here you are using delete
:
delete (nEncodedBytes);
This should be:
delete [] nEncodedBytes;
Using the []
for of new
with the non-[]
form of delete
invokes Undefined Behavior. Now in reality, all the compilers & platforms I'm aware of will handle this fine and do what you expect in this particular case -- but you should never rely on Undefined Behavior.
Now for your use of malloc
and free
:
I am unsure why I was using delete in one place, and free in the
other.
You probably shouldn't be. Here's a rule of thumb:
In C++, always use new
and delete
; never use malloc
and free
.
Yes, there are exceptions, but they are first of all rare, and second of all you will know exactly when the exceptions come in to play. In the example you've posted here, I see no reason that compels the use of malloc
and free
. Hence, you should not be.
Contrary to (popular?) belief, mixing new
/delete
and malloc
/free
in a single C++ program does no in itself invoke Undefined Behavior or make your program otherwise ill-formed. You can do it, if you do it properly. But you still shouldn't.
Is there a memory leak?
Well, since you have invoked Undefined Behavior, there could be. Undefined Behavior means anything can happen. You are however de-allocating everything you allocate in the code shown. So aside from the UB, I see no memory leak here.