Lab 11: Using dynamically-allocated memory

The goal of this lab is to use the functions malloc(), calloc() and free() for allocating and deallocating dynamic memory.

1. Introduction

Chatter is coming out with a new version, Chatter 2.0. The new system features

Your task is to revisit lab 3 but with these new features.

2. Set up

Get the starter code from the class directory.

cp /homes/tvandrun/Public/cs245/lab11/* .

3. Your tasks

Similarly to lab 3, you need to finish the message struct and write the basic operations for it. What is different is that now the type message is a pointer type, and other parts will involve working with pointers and dynamically allocated memory. Look over message.h and the driver programs.

A. Writing the struct

In message.h, finish writing the struct message_t. Remember that since messages can be any size and the number of hash tags is arbitrary, these can't be static arrays.

B. Making a new random message

Make a new file message.c to implement the functions prototyped in message.h, and implement the function newRandomMessage(). Use functions randomIne(), getTimeMillis(), fillRandomText(), getRandomHashTag() and fillRandomUserName() from chatterUtil for the data. Every message from fillRandomText() has 140 characters or fewer; you will need to allocate the space for the string (character array) dynamically, but it won't hurt to make the array larger than the string.

C. Displaying a message

Implement display() to format a message nicely, showing username, date, and hash tags. At this point you can use displayDriver.c to test what you have done so far.

D. Allocating memory for an array of messages

In mainDriver.c, allocate and array of (pointers to) messages in the indicated place. You can use this driver to test things as you go from here on out by commenting out the pieces you haven't tested yet; In this case, comment out from the call to sortByDate() on.

E. Sort by date

In message.c, implement sortByDate(), which should take an array of (pointers to) messages and modify that array by sorting the mssages by their date.

F. Make digest

Implement the function makeDigest() in message.c. It takes an array of (pointers to) messages and a user name and it makes a new message whose text is the concatenation of the texts of all the messages by that user. All the hash tags are included also. It returns (a pointer to) the new message.

G. Add a hash tag

Implement the function addHashTag() in message.c. This should modify the given message by giving it a longer hash tag array, now including the given hash tag.


Thomas VanDrunen
Last modified: Thu Nov 4 11:39:22 CDT 2010