0
int evilFunction() {
  int* i = new int(9);
  return *i;
}

int main() {
  int num = evilFunction();
  return 0;
}

What causes memory leak in this example ?

I thought when the functions returns value 9, immediately the pointer (i) and value 9 (*i) will be deallocated from the memory only num ( primitive-variable ) and its value 9 will stay in the memory.

Ayxan Haqverdili
  • 17,764
  • 5
  • 27
  • 57
Ömer
  • 1
  • 1
  • 2
    Each `new` should have its `delete`. – Jarod42 Oct 31 '20 at 09:37
  • The address that `i` points at is never deallocated. `new` creates on the heap and leaving a scope can only deallocate stack. – Aziuth Oct 31 '20 at 09:40
  • Thanks for the answers. So, if we use "new" in a function, that allocated memory due to "new" will stay in memory even if the function is quitted . – Ömer Oct 31 '20 at 09:52
  • A pointer does not deallocate anything by it's own. the basic thing is this: if a variable is directly declared without `new` or `malloc`, it is on the stack. Variables on the stack are deallocated as soon as the scope in which they were declared is left (that pretty much defines the stack). On the other hand, everything allocated on the heap, by using `new` or `malloc`, won't *ever* deallocate on their own (well, save for quitting the program) and thus will leak if they are not manually deallocated. I strongly recommend you to read a tutorial on stack and heap. – Aziuth Oct 31 '20 at 10:04
  • Also, you talking about whether a *pointer* is deallocated is basically non-sensical. It might be easier if you think of a pointer as an integer which carries a value that happens to be an address. This value is removed when the scope of the pointer is left, but that value is only the *address*, not the content in the memory at that address. This is like shredding an envelope that contains a house address. The envelope is gone, the house is not. – Aziuth Oct 31 '20 at 10:07
  • And another thing which might help you: consider that a pointer does not have to be set by using `new`. For example, you could go like `int a = 9; int* b = &a;`. I hope you see why in this case it would be absolutely fatal if the removal of the pointer would result in the deallocation of the memory it points at. – Aziuth Oct 31 '20 at 10:10
  • Thanks Aziuth, for spending your precious time to make me understand . I understood all these things you wrote here. – Ömer Oct 31 '20 at 12:53

0 Answers0