Week 4 Notes — Memory

Saturday, Jan. 23 to Friday, Jan. 29

Week 4 Video (duration 2:41:23, a new record)

Today’s theme is removing the training wheels. Things about C that were hidden for the last three weeks by conveniences provided in cs50.h.

Although I have never heard of valgrind (the program that helps you detect memory problems), such programs are pretty common. Under the hood what they are doing is replacing malloc() and free() with functions that have more diagnostics.

Malan is oversimplifying how memory is reclaimed on modern operating systems. However, the habits he is asking you to build are very good ones. You should always be thinking about when memory you allocate is no longer used and then putting a corresponding free when the code gets to that point.

Determining when memory is no longer needed and and freeing it such a complex subject it is a subject of its own known as “garbage collection.” C is not a garbage-collected language. You, the programmer, are the garbage collector.

Java is a garbage-collected language. It is easy to write badly-performing programs that allocate unreasonable amounts of memory in either Java or C. However, in C you are in so much control that you can write very high-performing programs. In Java, even if you write very good code it will be kind of slow because the Java virtual machine does the garbage collection.

Personally, I prefer reference-counted languages that free resources as soon as their reference count goes to zero (rather than waiting for the system to do garbage collection). In practice, this gives the programmer the absolute control over memory that C has, but most of the convenience of Java. It also causes programs to fail-fast rather than after some arbitrarily-timed garbage collection sweep.

I leave “reference counting” and “automatic reference counting” as things for you to learn a little more about, but only if you are first feeling very confident about how malloc() and free() work.

Problem Set 4

The first of this week’s two problems is filter and it has two versions. Let’s do the easier version of filter. All that has to be done is to implement four filters in the file helpers.c. It is pretty necessary to watch the five short walk-through videos to know exactly what they want your filters to do.

Some 5x blowups of the four filters applied to (a portion) of stadium.bmp:

Stadium Filtered

On to recover. The idea here is that there are jpeg files that can be found within card.raw by looking for the 3 1/2 bytes of header that jpeg files always begin with and that are unlikely to occur randomly.

Here is my recover.c output:

Recover Output

Satisfyingly it recovers exactly 50 files which is exactly what we were told to expect from card.raw.