Do not focus on the fact that you are using pointers that much. Memory leaks are usually about memory that the pointer points to, not about the pointer itself.
In this code:
int x;
int *p = &x;
there is no memory leak since there is no memory that would require explicit deallocation (no memory that has been allocated dynamically). int x
is a variable with automatic storage duration that will be cleaned up automatically when the execution goes out of scope and int *p = &x;
is just a pointer that holds the address of the memory where x
resides.
But you are right that in code like:
Resource* r = new Resource();
if (something) {
return -1;
}
delete r;
there is a memory leak since there is a return path (exit path) that doesn't free the allocated memory. Note that the same would happen if the exception would be thrown instead of return
being called... ensuring that all resources are freed properly is one of the main reasons why you should learn more about smart pointers, the RAII idiom and try to prefer objects with automatic storage duration over dynamically allocated ones.