ELEC424/COMP424/ELEC553: Mobile & Embedded Systems

Home
Schedule
Labs
Resources

Lab 1: Part 2: Fixing Memory Leaks


Memory leaks are a common problem that most programmers do not fully understand. In this part, you'll gain experience with detecting and resolving memory leaks in unmanaged code (i.e., a simple C file), where memory are much more likely to occur than in managed code (e.g., Java).

We have provided a source file primes.c that calculates all of the prime numbers in a given range. Unfortunately, the programmer who implemented this was an extreme amateur and forgot to manage memory with care. As such, the code is riddled with memory leaks and wastes resources in a ridiculous fashion.

Of course you need a compiler like GNU GCC to compile and run the program. Google if you can't find it on your machine. Hint: apt-get.

To compile the program and run it:

$ gcc -o primes primes.c
$ ./primes

Without changing the actual design of the code, fix the program so that no memory is leaked. By that, we mean that you should not rewrite the entire program from scratch, but merely change or add memory management code (e.g., allocations) to eliminate leaks. Make sure you document each leak, as well as your thought process in the report.

If you're unfamiliar with the concept of a memory leak, your previous code was probably quite leaky. Be sure to read up and understand the concept on Wikipedia or elsewhere.


Hints

If you're good, memory leaks can be found by manually inspecting the source code. If you're stuck, many tools exist to help you debug memory leaks, such as profilers. Google is your friend :-)


Writing the Report

In your report, please include in a detailed list of what memory leaks existed in the primes.c file, a description what tools you used to debug memory leaks, and your thought process when manually inspecting the source code, if applicable.

Also explain how you resolved each memory leak in the code, and why it was an actual leak in the first place. Example: “On line ##, a leak was caused because X bytes of memory were allocated, when only Y bytes were needed. I resolved this by changing the allocation parameters.”