In this lab weβre making hashtables in C. Weβve been using C arrays for the past two labs and now that Lab 4 has given us a working linked list in C, we can implement a hash table.
Β
You will be doing the following:
- TODO1 implement the hash table
- (EXTRA CREDIT) TODO2 No memory leaks
βΒ Β valgrind will display the following message:
All heap blocks were freed β no leaks are possible
Hash Table Refresher
Put simply, a hash table is just an array that is able to store data associated with a key. In Assignment 4 we were storing data using a βStringβ for our keys and an βΒ Β Β Β Β Β Β Β Β Β βObjectβ forβΒ Β Β Β Β Β Β Β Β our value, which would eventually be a list. The reason we want to make an array of lists instead of just using an array is it is much more efficient with storage space since we donβt need to make space in an array for every possible hash value. Additionally we donβt have to worry about running out of space in the array to deal with collisionsβ β, two keys being turned into the same array index.
Β
Recall that in Assignment 4 we needed to call the Java function βhashCode()β on our Stringβ key and then turned the hash code (named βhashCode in the PDF) into an indexβΒ Β Β Β Β Β Β into out hash table (making it between β0β and βtableSize β 1β.
Β
Stringβ βkeyβ = ββhelloββ; intβ hashCode = βkeyβ.hashCode();
intβ arrayIndex = Math.βabsβ(hashCode) % tableSize;
Β
At a high level this code is converting a βStringβ into a valid array index. What hashCode()β is doing behind the scenes involves, at least in C, getting a bit closer to the actual data representation in memory.
Hashing in C
Our βhashβ()β will actually be made up of three functions:
- intβ hash(Dictionary D, βcharβ* βkeyβ)
- The function that will return an array index
- unsignedβ βintβ βpre_hashβ(βcharβ* input)
- This function converts a string into an βunsignedβ βint
β unsignedβ βintβ βrotate_leftβ(βunsignedβ βintβ value, βintβ shift)
βΒ Β Β The function responsible for moving bits to semi-randomize the resulting key
Β
Note: βYou will only need to call βhash(Dictionary D, βcharβ* βkeyβ)β when you want to compute a hash value.
Β
These functions, included in the βDictionary.cβ file are defined as follows:
Β
| unsigned βintβ βrotate_leftβ(βunsigned βintβ βvalueβ, βintβ shiftβ) { intβ sizeInBits = β8β * βsizeofβ(unsigned βintβ); shift = shift & (sizeInBits β β1β); ifβ(shift == β0β){
returnβ βvalueβ; } returnβ (valueβΒ Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β β << shift) | (βvalueβ >> (sizeInBits β shift)); } |
Β
| unsignedβ βintβ βpre_hashβ(βcharβ* input)β { unsignedβ βintβ result = β0xBAE86554β β//this may correspond to an
address whileβ (*input) { result ^= *input++; result = rotate_left(result, β5β); } returnβ result; } |
Β
intβ hash(Dictionary D, βcharβ* βkeyβ) { returnβ pre_hash(keyβΒ Β Β Β Β β) % D->tableSize; }
Β
Note: βYou will only need to call βhash(Dictionary D, βcharβ* βkeyβ)β when you want to compute a hash value.
Β
A few things to note about these functions are that they are manipulating the actual bits of our data in memory, specifically the β&β, β<<β, β>>β, and β^=β operators which are defined as follows:
- &β is βbitwiseβ AND
- Instead of looking at a truth value it looks at the binary representations of its arguments and creates a new binary number using a logical AND for each bit (if you have taken CE12 you will be familiar with this).
- <<β and β>>β are bit shifts
- All data is represented as some sequence of bits in memory. Doing a left or right shift moves the bit sequence stored in a given variable (on the left) the specified number of bits (on the right) and fills in 0s when there is no more of the original value to shift into a bit.
- ^=β is a bitwise exclusive or assignment
- This operator performs the XOR operation between its two arguments and assigns the result to the left hand side.
Β
Wikipedia has a more in depth explanations of bitwise operators if youβre curious (βhttps://en.wikipedia.org/wiki/Bitwise_operations_in_Cβ)
Β
We have also included a program called βHashDemo.cβ to show how the above three functions work. To compile it, simply enter the following:
Β
bash$β gcc -std=c99 -o HashDemo HashDemo.c
Β
To run the program:
Β
./HashDemo
Β
It will show you a breakdown of strings and their indices as created by the above functions, the functionality of βrotate_left()β on a single unsigned int, and the number of bits a single character takes up.
A Note on typedefs
In this lab weβll also be seeing more of these statements and itβs one of the built in abstractions in C. Weβve done βtypedefβ βstructβ βnode_typeβ {β¦} Node;β to allow us to refer to a βNodeβ without having to repeatedly say βstructβ. Inside of βDictionary.hβ and Dictionary.cβ are two other βtypedefβs, one for a βstructβ βDictionaryObjβ*β and one for a βstructβ βEntryObjβ*β. These allow you to refer to pointers by whatever name was given after the βtypedefβ, in this case DictionaryβΒ Β Β Β Β Β Β Β is another name for a pointer to aβΒ Β Β Β Β Β Β Β Β Β Β DictionaryObjβ and βEntryβ is another name for a pointer to an βEntryObjβ.
TODO1: Implementing the Hash Table
Similar to Assignment 4 youβll be implementing something resembling the βMyHashtable class but not quite because, once again, C does not have classes. The basic blueprint for our C version should look very familiar:
- A βstructβ defined in the βDictionary.cβ called βEntryβ (a lot like the βNodeβ struct you implemented in Lab 4). It will once again store Key/Value pairs:
β charβ* βkey
β charβ* βvalue
β As before it should have an associated βEntry βnewEntryβ(βcharβ* key, charβ* valueβ β)β function
βΒ Β As weβre in C it should also have an associated βvoidβ freeEntry(Entry* pE)β function (more details about this in TODO2).
- Again like in Assignment 4 your hash table struct will have properties that arenβt directly accessible outside of the βc file:β
- intβ tableSizeβ β the size of the array being used by the hash table
β intβ sizeβΒ Β Β β β the number of key/value entries currently in the hash table
β List*β* βtableβ β an array of pointers to βListβs. As in Assignment 4, the reason for this is to handle cases where two keys have the same hash value.
- Youβll be implementing the following functions in βcβ:
- Dictionary newDictionaryβ (β intβ tableSize)β
β Β Β Β Allocates space for a new βDictionaryβ, initializes the new Dictionaryββs variables, and returns it
β voidβ freeDictionary(Dictionary* pD)
β Β Β Β Frees all data associated with the βDictionaryβ pointed at by βpD (more detail about this in TODO2)
β int isEmptyβ(Dictionary D)
β Β Β Β Returns an βintβ; booleans in C are integers. Traditionally a β1 represents βtrueβ and β0β represents βfalse
β int β sizeβΒ Β Β Β Β Β Β (β Dictionary D)
β Β Β Returns the number of key/value pairs in D
Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β β voidβ insertβΒ Β Β Β Β Β Β Β Β Β Β Β Β Β Β β(Dictionary D, βcharβ* key, βcharβ* value)
β Β Β Β Adds a new key/value pair into the dictionary using a linked list to deal with collisions (translating Assignment 4βs βputβ()β is a good place to start)
β charβ* βlookupβ(Dictionary D, βcharβ* βkeyβ)
β Β Β Β Β Β Β Returns the value in βDictionaryβ Dβ associated with βkey
(translating Assignment 4βs βgetβ()β is a good place to start)
β voidβ βdeleteβ(Dictionary D, βcharβ* key)
β Β Β Β Removes the βEntry associated with βΒ Β Β Β βkeyβ in DictionaryβΒ Β β D
(translating Assignment 4βs βremove()β is a good place to start)
β Β Β Β Remember that because weβre in C we need to free whatever was deleted here.
β voidβ βmakeEmptyβ(Dictionary D)
β Β Β Β Removes all Entries from Dictionary D (translating Assignment 4βs clearβ()β is a good place to start)
β Β Β Β Remember that because weβre in C we need to free memory weβre not using anymore ourselves
β voidβ βprintDictionaryβ(βFILE* βoutβ, Dictionary Dβ)
β Β Β Β Β Β Prints the contents of βDictionary Dβ to a file. More on this below.
Β
Each of the above functions has a brief description in βDictionary.hβ including specifics about return values and preconditions (what each function assumes to be true when itβs called).
Β
Making an Array of Lists and Notes About calloc
Because weβre in C, we donβt get to use the nice Java array syntax:
Β
MyLinkedList[] table = βnewβ MyLinkedList[tableSize];
Β
instead we need to do what we did in Lab 3 and use βcallocβ()β: βΒ Β Β Β Β Β Β Β Β First we need a pointer to a βList:β
Β
Listβ** βtable
Β
- Next, inside βnewDictionary()β weβll need to set our newly instantiated Dictionaryβs table pointer to point to something on the heap:
Β
callocβ(tableSize, βsizeofβ(List*))
Β
The reason we need table to be of type List** is because itβs an array of pointers to Listβs. Even though table looks a little strange compared to a Java array declaration and initialization, we can still access whatever is in it using the same array indexing weβve been working with (assume D is of type Dictionary):
Β
D->βtable[0] = make_list();
Β
To make a new instance of a βDictionaryObjβ we still need to call βmallocβ()β, which requires a pointer:
Β
Dictionary D = βmallocβ(βsizeofβ(DictionaryObj));
Β
Note: βOne important thing to remember about βsizeofβ()β is you want to give it the structβ not the pointer. So when we want to make a new dictionary, we donβt want to give βsizeofβ()β DictionaryβΒ Β Β Β Β Β Β Β , we want to give it βΒ Β Β Β Β Β Β DictionaryObjβΒ β because remember that Dictionaryβ is really just another name for a βDictionaryObj*β.
Β
A note on βprintDictionary()Β
Β
The function βvoid β βprintDictionaryβ(βFILE* βoutβ, Dictionary D)β β is a little more flexible than what weβve been doing in C up to this point since itβs able to take any arbitrary file and write to it. Instead of using βprintfβ()β which only lets us print to stdoutβ, we can use βfprintfβ()β which functions almost identically to printfβΒ Β β()β with one difference. A general call to βprintfβ looks like:
printf(ββ<format string>ββ, β<argument1>β, β<argument2>β,β¦, β<argumentn>β);
Β
while a general call to fprintfβΒ Β Β Β looks like:β
Β
fprintf(β<file name>β, ββ<format string>ββ, β<argument1>β,β¦, <argumentn>β);
Β
Similar to Lab 2 in Java, C treats standard in (βstdin)β and standard out (stdoutβΒ Β Β Β Β Β Β Β Β )β as files and youβll notice that the calls to printDictionary()βΒ Β Β Β in β DictionaryClient.cβ look likeβΒ Β Β Β Β Β Β this:
Β
printDictionary(βstdoutβ, A);
Β
Compiling and Running
As in Lab 4, we have a few different files we need to compile at once to have our object file actually work as intended. We also now have two different files for you to use to test your hash table: βDictionaryClient.c and βΒ Β Β Β Β Β Β Β Β DictionaryClient2.cβΒ Β Β Β . To compile themβΒ Β Β youβll need to run the following:
Β
bash$ gcc βDictionaryClient.β βcβ βDictionaryβ.βcβ list.βcβ βstd=c99 -o DictionaryClient
Β
to make the object file for DictionaryClientβΒ Β Β Β Β Β Β Β andβ
Β
bash$ gcc βDictionaryClient2β.βcβ βDictionaryβ.βcβ list.βcβ βstd=c99 -o DictionaryClient2
Β
To make the object file for DictionaryClient2βΒ Β Β Β Β Β Β Β .β
Β
DictionaryClient is fairly simple and should print the following to the console:
Β
two bar five happy one foo three blah seven blue four galumph six sad
key=ββoneββ value=ββfooβ key=ββtwoββ value=ββbarβ key=ββthreeββ value=ββblahβ key=ββfourββ value=ββgalumphβ key=ββfiveββ value=ββhappyβ key=ββsixββ value=ββsadβ key=ββsevenββ value=ββblueβ two bar five happy four galumph six sad key=ββoneββ not found ββ(null)β key=ββtwoββ value=ββbarβ key=ββthreeββ not found ββ(null)β key=ββfourββ value=ββgalumphβ key=ββfiveββ value=ββhappyβ key=ββsixββ value=ββsadβ key=ββsevenββ not found ββ(null)β false 4 true
Β
DictionaryClient2β does something a little more fun and loads each line of its own .c
file into the hash table and prints the hashtable to a file named DictionaryClient2-out, which should have the following contents:β
Β
| lineβ β53β: | Β Β Β Β Β Β key = &keyBuffer[keyBufferOffset]; |
| lineβ β36β: | Β Β Β Β Β Β value = &valBuffer[valBufferOffset]; |
| lineβ β63β: | Β Β Β freeDictionary(&A); |
| lineβ β18β: | Β Β Β βcharβ* value; |
| lineβ β45β: | Β Β Β Β Β Β key = &keyBuffer[keyBufferOffset]; |
| lineβ β11β: | Β β#define MAX_LEN 180 |
| lineβ β28β: | Β Β Β βwhileβ( fgets(βlineβ, MAX_LEN, in)!=NULL ){ |
| lineβ β55β: | Β Β Β Β Β Β insert(A, key, value); |
| lineβ β21β: | Β Β Β βintβ keyBufferOffset = β0β, valBufferOffset = β0β; |
| lineβ β38β: | Β Β Β Β Β Β valBufferOffset = valBufferLength; |
| lineβ β9β: | Β β#includeβDictionary.hβ |
Β
| lineβ β65β:Β Β Β free(valBuffer); lineβ β47β:Β Β Β Β Β Β keyBufferOffset = keyBufferLength; lineβ β31β:Β Β Β Β Β Β lineNumber++; lineβ β2β:Β β// DictionaryClient2.c
lineβ β13β: βintβ main(βintβ argc, βcharβ* argv[]){ lineβ β40β:Β Β Β Β Β Β β// put label in keyBuffer lineβ β57β:Β Β Β Β Β Β valBufferOffset += (strlen(value) + β1β); lineβ β23β:Β Β Β βcharβ βlineβ[MAX_LEN+β1β]; lineβ β50β:Β Β Β β// put keys and values in dictionary A lineβ β67β:Β Β Β fclose(out); lineβ β49β:Β lineβ β33β:Β Β Β Β Β Β βlineβ[lineLength] = ββ\0ββ;Β β// overwrite newline β\nβ with null β\0β lineβ β60β:Β Β Β printDictionary(out, A); lineβ β15β:Β Β Β FILE* in = fopen(ββDictionaryClient2.cββ, ββrββ); lineβ β42β:Β Β Β Β Β Β labelLength = strlen(label); lineβ β59β:Β lineβ β5β:Β Β Β lineβ β70β: } lineβ β25β:Β Β Β βintβ i, labelLength, lineLength, lineNumber = β0β; lineβ β52β:Β Β Β βforβ(i=β0β; i<lineNumber; i++){ lineβ β69β:Β Β Β βreturnβ(EXIT_SUCCESS); lineβ β35β:Β Β Β Β Β Β valBuffer = realloc(valBuffer, valBufferLength*βsizeofβ(βcharβ) ); lineβ β62β:Β Β Β β// free memory and close files lineβ β17β:Β Β Β βcharβ* key; lineβ β44β:Β Β Β Β Β Β keyBuffer = realloc(keyBuffer, keyBufferLength*βsizeofβ(βcharβ) ); lineβ β7β:Β Β β#include<stdlib.h> lineβ β10β: lineβ β27β:Β Β Β β// read input files lineβ β54β:Β Β Β Β Β Β value = &valBuffer[valBufferOffset]; lineβ β20β:Β Β Β βcharβ* valBuffer = NULL; lineβ β37β:Β Β Β Β Β Β strcpy(value, βlineβ); lineβ β8β:Β Β Β Β Β Β β#include<string.h> lineβ β64β:Β Β Β free(keyBuffer); lineβ β19β:Β Β Β βcharβ* keyBuffer = NULL; lineβ β46β:Β Β Β Β Β Β strcpy(key, label); |
| lineβ β30β:Β Β Β Β Β Β β// put line in valBuffer lineβ β1β:
//ββββββββββββββββββββββ- βββ- lineβ β12β:Β lineβ β29β: lineβ β56β:Β Β Β Β Β Β keyBufferOffset += (strlen(key) + β1β); lineβ β22β:Β Β Β βintβ keyBufferLength = β0β, valBufferLength = β0β; lineβ β39β: lineβ β66β:Β Β Β fclose(in); lineβ β48β:Β Β Β } lineβ β32β:Β Β Β Β Β Β lineLength = strlen(βlineβ)β-1β; lineβ β3β: β// Another test client for the Dictionary ADT lineβ β14β:Β Β Β Dictionary A = newDictionary(); lineβ β41β:Β Β Β Β Β Β sprintf(label, ββline %d:\tββ, lineNumber); lineβ β58β:Β Β Β }Β lineβ β4β: //ββββββββββββββββββββββ- βββ- lineβ β24β:Β Β Β βcharβ label[MAX_LEN+β1β]; lineβ β51β:Β Β Β keyBufferOffset = valBufferOffset = β0β; lineβ β68β: lineβ β34β:Β Β Β Β Β Β valBufferLength += (lineLength+β1β); lineβ β61β: lineβ β16β:Β Β Β FILE* out = fopen(ββDictionaryClient2-outββ, ββwββ); lineβ β43β:Β Β Β Β Β Β keyBufferLength += (labelLength+β1β); lineβ β6β:Β β#include<stdio.h> lineβ β26β: |
Β
Memory Management
Weβve now done two labs in C and have a bit of experience doing manual memory management so youβll notice that our βfreeDictionary()β function is asking for something a little odd, a βDictionary* (remember that βΒ Β Β Β Β Β Β βDictionaryβ is another name for DictionaryObj*β). The same is true of βfreeEntry()β wanting an βEntry*β rather than an Entry (another name for βΒ Β Β Β Β Β βEntryObj*)β . The reason for this is to allow the function thatβΒ Β Β Β Β is responsible for freeing memory to also be able to set the pointer that is pointing to the freed memory to NULLβ. Put more simply, itβs an emulation of the way deleting something in Java works since in Java you donβt have to worry about a reference pointing to deallocated memory.
Β
What does this mean for you? If you look at either of the βDictionaryClient.cβ files youβll notice that their calls to βfreeDictionary()β use β&Aβ. β&Aβ means weβre getting the address of βAβ, which is of type βDictionaryβ (really a βDictionaryObj*β). So when we say freeDictionary(&A)β, weβre passing it the pointer to a pointer, which is what freeDictionary() wants.β
Β
When weβre actually writing our destructor method, instead of simply freeing what we were passed as we have done before with List:
Β
| voidβ βfree_nodeβ(Node* node)β{
βfreeβ(node->data); βfreeβ(node); } |
Β
as an example, we need to dereference the pointer to the pointer. In freeDictionary()ββs case βpDβ is a pointer to a pointer to an instance of a DictionaryObj:
Β
&pD->pDβ->βinstanceβ βofβ βDictionaryObj
Β
If all we have is β&pD, how do we get to our instance? We can use the βΒ Β Β Β Β Β Β Β β*β operator to dereferenceβ &pDβΒ Β Β Β Β β like this:
Β
(*pD)
Β
Once we have (β*pDβ), we can treat it just like a regular pointer! But because we also have β&pd (the pointer to the pointer), this allows us to set βΒ Β Β Β Β Β Β Β Β Β Β pDβ to β NULLβ β inside theβ freeDictionary()β functionβ.
Β
Note:β Remember that the βListβ we built in Lab 4 uses a voidβΒ Β Β Β *β for data and since weβllβΒ Β Β be storing an βEntry in a β NodeβΒ Β Β β struct, weβll need to loop through the βListβ calling freeEntry()β on each Nodeβs data pointer. Once we finish freeing each βEntry, β βthen weβre allowed to call βfree_list()β.
Β
Reminders About valgrind
Make sure youβre running valgrind as follows for both DictionaryClient and DictionaryClient2:
Β
valgrindβ ββleak-check=full -v ./DictionaryClient
Β
valgrindβ ββleak-check=full -v ./DictionaryClient2
Β
The important things to look out for (after segmentation faults) is that the number of allocations and the number of frees should be the same. Generally when these are equal you wonβt have any memory leaks, though the βin useβ report at exit part of the HEAP SUMMARY will give you a more detailed breakdown.
Β







