Lab 7: Dynamic allocation in C

The goal of this lab is to practice working with pointers, dynamic allocation, and strings in C.

You will write some functions for a "homemade string" library.

1. Set up

Copy the given code for this lab:

mkdir lab7
cd lab7
cp ~tvandrun/Public/cs245/lab7/* .

2. Inspecting the code

Consider the two functions that are written for you.

3. Implementing the remaining operations.

hmstrlen().

"Homemade string length." Write an imitation of the standard string function strlen() that takes a pointer to the beginning of the string and computes its length---the number of characters before the end-of-string marker.

hmstrcat().

"Homemade string concatenation." Unlike the string concatenation operation in Java, C's strlen() does not make a new string. Notice the return type here is void. Instead it modifies the area of memory pointed to by the first parameter. Specifically, it finds the end of the string that starts at that first address and then copies the contents of the string pointed to by the second paremeter at the end of the first string. Write an equivalent implementation for hmstrcat()

hmstrcat2().

Now, just for fun, write a second version of "hommade string concatenation" that works more like string concatenation in Java. Do not modify either of the strings given, but instead, allocate a new dynamic charater array, big enough to handle all the characters in both strings total, and then copy all the characters from the old strings to the new. Finally, return the pointer to this newly allocated character array.

4. Testing your code

I have provided a makefile to compile your code and two driver programs.

Running make will compile hmstring.c and will also produce the excutable for hmstrexample, which runs various tests on your functions.


Thomas VanDrunen
Last modified: Thu Oct 11 13:10:46 CDT 2012