0

I know that whenever we allocate something into the heap, we must delete it. So I have a question, which I'll explain with help of an example.

Let's say size is a function that uses the new operator.

int size (...){
       ...
       int *p = new int[1];
       *p = 5;
       ...
       return *p;
}

I have allocated some memory in the heap so I must delete it, but if in my main function I do this...

int main(){
     int i = 0;
     if (i < size(...)){     // <- here
         ...
     }
}

As you can see I am not assigning size(...) to anything. My question is can we deallocate memory in such a situation, if yes then how?

  • No, you can't delete that memory, sinc you have no longer access to the pointer needed for the corresponding `delete`call. – πάντα ῥεῖ Apr 24 '21 at 01:06
  • 1
    When `size()` returns, the pointer `p` (which holds the pointer resulting from the `new` expression) ceases to exist. So that dynamically allocated memory cannot be released, and will be leaked. And assigning the return value from `size()` to something would not change that, since the return value of `size()` is a COPY (i.e. a distinct variable) of the value that your code stored in `*p`. – Peter Apr 24 '21 at 01:07
  • Dude @πάνταῥεῖ ῥεῖ I don't understand classes yet, please don't close my question, can you open it again. – black mamba Apr 24 '21 at 01:16
  • @Peter what should be the best practice? If we want to use new in our function. – black mamba Apr 24 '21 at 01:17
  • @blackmamba Nothing to do with classes. It's all well explained in the duplicate. I'll not reopen your question unless you [edit] it to explain in more depth why the answers in the duplicate don't apply well for your problem. – πάντα ῥεῖ Apr 24 '21 at 01:19

0 Answers0