liveBook · Manning

Memory leak

As explained in .NET in Action, Second Edition

A memory leak is a condition in which memory remains allocated or unreachable despite no longer being needed by a program.

A memory leak occurs when heap memory is no longer needed but is not returned for reuse. In a C++ program, losing the last pointer to an allocated array without freeing it can leave that memory unavailable. Repeated allocations may eventually exhaust the heap. section 10.3.4

Listing 10.8 C++ code to read numbers into a dynamic array
int* readNInts(int count) {
  int* ptr;                           #1
  ptr = new int[count];               #2
  for (int i = 0; i < count; i++) {
    ptr[i] = readInt();               #3
  }
  return ptr;                         #4
}

The C++ function allocates an array with `new` and returns its pointer. Whoever finishes using the array must release it with `delete[]`; losing the pointer first makes that allocation a leak. section 10.3.4

Explicit memory management offers control but adds work to development and testing because leaks can be difficult to find. C# arrays are also allocated on the heap, but .NET uses a garbage collector to manage memory instead of requiring this `delete[]` step. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Defines a leak through unfreed allocation and a lost pointer, without developing a leak-diagnosis procedure.
Examples
Uses a C++ dynamically allocated integer array and its C# array counterpart.
What it assumes
Builds on arrays and pointers to discuss heap allocation and freeing.
What you can do after
Diagnose/debug with it by recognizing when allocated C++ array memory is not freed before its pointer is lost.
How it connects
Connects memory leaks to heap allocation, pointers, explicit freeing, and garbage collection.

Also explained in

Compare how 5 books explain memory leak →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.