Help finding memory leak?

Hello, I have found that a part of my code meant to be an optimization makes my programs run out of memory. Here is the relevant part of code:

  TVectorD pre = smoothed_bwd(ampl_tv,pre_frames);
  TVectorD post(n_samples);
  if( pre_frames == post_frames )
    {
      post = *(TVectorD*)pre.Clone();
    }
  else
    {
      post = smoothed_bwd(ampl_tv,post_frames);
    }

In this case, ampl_tv is a TVectorD passed into a function (where this code lives), smoothed_bwd is a function that returns a TVectorD, pre_frames and post_frames are integers. If I remove the if/else statement and just calculate post = smoothed_bwd(ampl_tv,post_frames) regardless, the programs finish with a more “normal” memory footprint. Why is the (TVectorD)pre.Clone() line causing a memory leak? I’m not using “new” without “delete” or anything, afaik… Would a fix just involve doing post.Delete() before the function returns? Is there a better way to copy the TVectorD pre in the case where post == pre?

Thanks,
Jean-François

Do you understand, why the following code fragment produces memory leak?

...
int i = 0;

....

i = *(new int(10));
...

Anyway, just use assignment operator instead of this weird expression with Clone.
And that’s really interesting, at some point you use assignment operator already, like in post = your_function(),
and at some point you suddenly call Clone.

The reason I was using clone is that I wanted an independent copy of the vector. I didn’t realize that by simply doing post = pre, the contents of pre would get copied into post. I guess I’ve been doing too much python, where such an operation would result in two names “pre” and “post” for the same underlying data.

Thanks for the recommendation.

[quote=“jfcaron”]The reason I was using clone is that I wanted an independent copy of the vector. I didn’t realize that by simply doing post = pre, the contents of pre would get copied into post. I guess I’ve been doing too much python, where such an operation would result in two names “pre” and “post” for the same underlying data.

Thanks for the recommendation.[/quote]

Yes, C++/C are very different from python in this respect. pre and post are not references, but values, so they are already independent copies, even after assignment.