CS61C Lab 3




This lab will give you practice working with the malloc function.


  • K&R: 6.1-6.5



Working with a partner is highly recommended. If you work with a partner, be sure both partners understand all aspects of your solution.


Copy the contents of ~cs61c/labs/03 to a suitable location in your home directory.

$ mkdir ~/lab
$ cp -R ~cs61c/labs/03/ ~/lab

Exercise 1: part1.c

Open part1.c. Describe (either as comments in this file or a separate document) the effect of each of the statements and answer the following questions:

  1. What areas of memory (heap or stack) are affected by the statement?
  2. Does any memory get allocated or freed?
  3. If so, where is this memory?
  4. Does the statement result in a memory leak?

Feel free to use gdb or printf statements to help in your investigation. Additionally, both of the malloc statements work, but one of them is in bad form. Which is "bad," why is it "bad," and how would you change it?


Show your answer to your TA. 

Exercise 2: vector.c

In vector.c, we provide you with a framework for implementing a variable-length array (in Java and C++, these variable-length arrays are known as the Vector class). This exercise is designed to help familiarize you with C structs and memory management in C.

Fill in the missing code (you only need to modify vector.c), and test it by running 'make test'. If the test breaks, try using gdb (or ddd) on the created executable (vector.test) or printf statements to find your bugs. If you have extra time, you can try adding more test cases to the code in test.c and explore how we've split up this one program into two different .c files.

Comments in the code describe how the functions should work. Look at the functions we've filled in to see how the data structures should be used.

For consistency, it is assumed that all entries in the vector are 0 unless set by the user. Keep this in mind as malloc() does not zero-out the memory it allocates.


Run vector.test and show it to your TA 
Show your TA your modifications in vector.c