Do pointers always lead to memory leak or they are deleted when they go out of scope?

c++, dynamic-allocation, memory-leaks, memory-management, pointers

Solution

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.

Problem

I'm studying c++ and I'm reading about pointers. I'm curious about the following scenarios: Scenario 1: If I'm not mistaken, if the user types `-1`, there will be a memory leak: ``` #include <iostream> using namespace std; int main(){ int *p = new int; cout << "Please enter a number: "; cin >> *p; if (*p == -1){ cout << "Exiting..."; return 0; } cout << "You entered: " << *p << endl; delete p; return 0; } ``` Scenario 2: But what happens in the following code? From what I've read and correct me if I'm wrong, when declaring a pointer like in the second scenario the pointer gets cleared out once you are out of scope. So if the user doesn't enter `-1`, the `*p` will be auto-cleared? ``` #include <iostream> using namespace std; int main(){ int x; int *p = &x; cout << "Please enter a number: "; cin >> *p; if (*p == -1){ cout << "Exiting..."; return 0; } cout << "You entered: " << *p << endl; return 0; } ``` What happens if I enter `-1` in the second scenario?

Original source

Related problems