0

Is there some good example code to show poor memory management (e.g. the programmer assumes there is garbage collection)?

I would like to demonstrate this during class. The VM we're using has 16 available hardware threads.

Kyle
  • 554
  • 3
  • 10

1 Answers1

2

Recent work in Chapel has been trying to reduce the number of cases where a programmer might unwittingly leak memory (for example, see the section on delete-free programming in the release notes for Chapel 1.18). That said, allocating instances of unmanaged classes is a way to generate an intentional memory leak:

// run with --memTrack in order for the memoryUsed() call to work
use Memory;

class C {
  var A: [1..1000000] real;
}

for i in 1..1000000 {
  var myC = new unmanaged C();
  writeln(memoryUsed());
}

Specifically, the compiler is not responsible for freeing instances of unmanaged classes; the user must do so via the delete statement. Failure to do so will cause the memory for that class to be leaked.

Therefore, a leak-free version of the above would be:

// run with --memTrack in order for the memoryUsed() call to work
use Memory;

class C {
  var A: [1..1000000] real;
}

for i in 1..1000000 {
  var myC = new unmanaged C();
  writeln(memoryUsed());
  delete myC;
}
Brad
  • 3,839
  • 7
  • 25