Is a pointer pointing to another array and deallocating memory at the end considered as memory leak in c++?
I want you to picture yourself in the following scenario
- You are standing next to an abyss with one arm tied behind your back. Thus, you have one hand available. That hand is your
pointer
var. - At some point you request of me to throw you a ball. That ball is the memory being allocated via
new
. - I toss you the ball, which you catch with your one free hand. You don't "own" the ball per se, but it is entirely on loan to you, and is your exclusive responsibility. I'm trusting you to toss it back if/when you don't need it anymore.
- Now, you request I throw you a different ball, a new
new
, if you will. - I do so, and you catch the new ball, but to do so you first drop the old ball (pun intended; yes, you "dropped the ball"). It falls into the abyss. Where it ultimately ends up nobody knows. But now you are holding the second ball.
- Now the time comes to return the balls I've handed out to you. You toss me the one you still have, good. But the first one is gone forever. It is in no one's hand, and no one knows where it is.
That is a memory leak.
It can be circumvented a number of ways.
- You could toss the ball back to me before you request the new one.
- You could break the shackles that bind your other arm, and catch it there. Now you have two balls in two hands (e.g. two allocations held in two pointers), both of which you will (hopefully) someday toss back to me once finished with them.
- You could use a hyped up prototype ball that has auto-magic super-homing-beacon logic, so if ever tossed to the side it does not fall into the abyss. Instead, it knows how to find its way back to me all on its own. (smart pointer).
- You could use a special ball that knows how to instinctively ask me for more size when needed (to a point). (a
std::vector
for example) - etc.
Yes, you have a memory leak. A blatant one. You can solve it by returning the memory via delete[]
before asking for more. You can solve it by using more than one pointer and managing them both. You can solve it using intelligent constructs like smart pointers to assist in lifetime management. Or you can do what modern C++ programmers do: use RAII tactics to let the code, and intelligent containers, manage things mostly for you.
Regarding realloc
... just don't. realloc
is a C mechanic for resizing buffers (and even allocating them if need be). But it does not know one iota about the characteristics of complex entities being stored within. Failure to properly construct and destruct objects with such complexity spells disaster whence later referenced.
In the long run, embrace the concept of programming in a different language, with different patterns and methodologies. C doesn't have all these whiz-bang containers like std::vector
; you do. C doesn't have smart pointers; you do. Etc. Embrace that early and often. It will pay for itself many times over down the road.