University of California at Berkeley

College of Engineering

Department of Electrical Engineering and Computer Science



EECS 61C, Summer 2006


Lab 3: Malloc


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

Initial preparation

Read sections 6.16.5 in K&R.

Copy the directory ~cs61c/labs/03 to your home directory.

Working with partners (highly recommended)

If you work with a partner on these exercises, make sure that you both understand all aspects of your solutions.


Part 1


Open part1.c. Here are the instructions found in the file itself:
Describe (either as comments in this file or a separate document) the effect of each of the following statements. What areas of memory (heap or stack) are affected by the statement? Does any memory get allocated or freed? If so, where is this memory? 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?


Part 2


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 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.