Dangling Pointers and Memory Leaks

Dangling pointers

Before we saw that we can pass a reference to another variable to a special variable that points to a location in memory. A dangling pointer occurs when a we create a variable that points to the location of another variable but that variable falls out of scope. It looks like this

int main() {
    int* ptr;
    dangling_ptr(ptr);
}

void dangling_ptr(int* ptr) {
    int num = 0;
    ptr = #
    // num falls out of scope, not the pointer points to something that doesn't
    // exist!
}

So overall lesson, be very careful when creating pointers.

Memory Leaks

In cpp memory leaks are a big thing that often cause things like the blue screen or death or crippling crashes.

A memory leak occurs when you forget to free your heap allocated memory and the memory still exists even after the variable falls out of scope.

This is easier seen with examples of common occurences in competitive programming.

// loop with memory leak
int main() {
  for (;;) {
    int* arr;

    int size;
    std::cin >> size;
    arr = new int[size];

    for (int i = 0; i < size; i++) {
      arr[i] = i;
    }

    // memory leak occurs here since arr is about to fall out of scope,
    // but the memory was not freed, therefore the allocated values still exist!
  }
}

// loop memory safe
int main() {
  for (;;) {
    int* arr;

    int size;
    std::cin >> size;
    arr = new int[size];

    for (int i = 0; i < size; i++) {
      arr[i] = i;
    }

    // we free memory so no more memory leaks
    delete [] arr;
  }
}

as a rule of thumb, there are ways to program without calling new or delete, and unless you need fine grain control on your pointers, using them should generally be avoided.