What is a memory leak?
Memory leak made simple: whenever you allocate memory with malloc/new and don't deallocate it later with free/delete after finishing using that memory... will cause a memory leak! The allocated memory will remain there and that space won't be used by your program ever again.
This is a serious problem when the leak is on a function that is called many times, rendering the leak to grow larger and larger each time the function is called.
Seems like you do understand it - with one exception: In your example, len is a stack variable like everything else. new
or malloc
create on the heap, everything else (local variables etc) is on the stack. And main's local variables are not different from any other function's variables.
Shared memory is a rather rare case, you usually don't need it and therefore you won't have it unless you explicitly ask for it (otherwise, some random other process may use the very same memory your process uses - obviously, this would break things badly).
Your function variables are also on the stack usually, not the heap. In most systems, the heap is used for dynamic allocations. The usual memory leak situation is
- Call some function F
- F allocates (new or malloc) some memory
- F returns to caller (no delete/free)
- pointer pointing to the dynamically allocated memory is out of scope
- the memory is still allocated.
- You can't delete/free it anymore