What is a memory leak?

前端 未结 8 2080
无人共我
无人共我 2020-11-27 05:50

Obviously Wikipedia has a fair amount of information on the topic, but I wanted to make sure I understand. And from what I can tell it\'s important to understand the stack/h

相关标签:
8条回答
  • 2020-11-27 06:35

    In general, automatic variables in functions (subroutines) are going to be stored on the stack as well. Only 'malloc' or 'new' data allocations come from the heap. Next, heap based allocations can be freed and reused (many times) before the end of the program. The allocation system keeps track of both the in-use areas and the freed areas. Finally, a memory leak is when your program has lost track of some allocated memory without freeing it. this can happen by either writing over a pointer with a new value, or storing a pointer in a variable with limited lifetime/scope.

    0 讨论(0)
  • 2020-11-27 06:41

    It looks like you're using C++ code. In C++ local variables are put on the stack (I'm guessing that globals are too, but I'm not sure). So len in your middleLetter function would be put on the call stack as well. I recommend reading this article: http://en.wikipedia.org/wiki/Call_stack

    When you use the new operator with a type, like int *x = new int; for example, enough contiguous memory is found to put an int. The pointer that you use to reference it, *x, is a local variable though. If x goes out of scope and you lose your pointer, that does not free the memory on the heap. That memory is still "used" by your program even though you now have no way to reference it. Because you cannot reference it you cannot deallocate it (or delete it).

    As you continue to do this you will eventually run out of space on the heap that you can allocate to, and you're program will get close and closer to blowing up because it has no memory to work with among other problems.

    0 讨论(0)
提交回复
热议问题