CS50 Debugging Tools
Memory, Pointers, and Data Structures in C
Debugging and Code-Quality Tools
Several tools help identify different categories of programming problems. Each tool provides information that is difficult or tedious to obtain by simply rereading source code.
debug50
debug50 is a graphical debugger for C programs. It allows a programmer to:
Set breakpoints at specific lines.
Pause execution at those breakpoints.
Execute a program one line at a time.
Inspect the current values of variables.
Follow the program’s control flow.
Observe how function calls create and remove stack frames.
The debugger is especially useful when the programmer needs to understand the exact sequence of operations leading to a bug.
A breakpoint can be placed deeper in a loop or function to avoid repeatedly stepping through irrelevant code. This is often more efficient than starting at the beginning and clicking through many iterations.
check50
check50 automatically tests the correctness of a program. It runs a collection of test cases similar to those used by course staff when evaluating solutions.
It is useful because it:
Automates repetitive testing.
Checks expected outputs and behaviors.
Can reveal errors that are not obvious from a few manual examples.
However, check50 cannot test every possible problem. A program may pass the provided tests while still containing bugs, especially memory-related bugs.
printf
printf is useful for more than displaying the final output required by a program. It can be used as a debugging tool by printing:
Variable values.
Messages indicating that execution reached a particular line.
Intermediate results in a calculation.
The number of times a loop has executed.
Values produced during nested-loop iterations.
For example, a programmer may place a printf inside a loop to determine whether the loop runs the expected number of times. This can be quicker than stepping through every iteration with a debugger.
style50
style50 checks the formatting and style of C code. It can identify issues such as:
Missing or unnecessary spaces.
Inconsistent indentation.
Formatting that reduces readability.
Good style makes code easier for both the original programmer and other programmers to understand and maintain.
help50
help50 is useful when a compiler or command-line tool produces an unfamiliar error message. It analyzes the command’s output and provides more accessible, teaching-oriented guidance.
A typical workflow is to place help50 before a command that is producing a confusing error. It can help interpret:
Compilation errors.
Incorrect command usage.
Missing files or arguments.
Common syntax and configuration problems.
Rubber-duck debugging
Rubber-duck debugging is a technique in which a programmer explains code aloud, step by step, to an inanimate object such as a rubber duck.
The programmer might explain:
What each line is intended to do.
What values variables contain.
What a function receives and returns.
How execution moves from one line to the next.
Why each operation should be logically correct.
The act of verbalizing the code often exposes an incorrect assumption or an operation that does not logically follow from the previous one. The object does not need to respond; hearing the explanation aloud can be enough to produce the insight.
Rubber-duck debugging works because explaining a program forces the programmer to make each assumption explicit rather than keeping several steps vague in their head.
Memory Errors and Valgrind
C gives programmers direct control over memory. This control is powerful, but it also creates responsibilities that higher-level languages often manage automatically.
Allocating memory with malloc
The function malloc allocates a requested number of bytes on the heap and returns the address of the allocated block.
For example, to allocate space for ten integers:
int *x = malloc(10 * sizeof(int));This requests enough memory to hold ten values of type int.
Important points:
sizeof(int)determines how many bytes one integer requires on the current system.Hard-coding a value such as 4 is unsafe because the size of an
intcan vary between systems.mallocreturns a pointer, not an integer value.The pointer stores the address of the first byte in the allocated region.
Because the allocated bytes are contiguous, the region can be treated similarly to an array:
x[0] = 50;
x[1] = 60;
x[9] = 70;If space was allocated for ten integers, the valid indices are:
Accessing x[10] is outside the allocated region.
Out-of-bounds memory access
An out-of-bounds access occurs when a program reads or writes beyond the limits of an array or allocated memory block.
For an array of ten integers:
x[0]throughx[9]are valid.x[10]is invalid.Negative indices are also invalid.
C often does not immediately report an error when an invalid access occurs. The program may appear to work because:
The operating system allocated a region larger than the program explicitly requested.
The memory immediately beyond the array happens to be accessible.
The invalid access changes memory that is not currently being used.
The particular computer’s memory layout happens not to trigger a crash.
This is accidental behavior, sometimes described as getting lucky. The same program may crash on another computer, under another operating system, or after unrelated changes to the code.
free and memory leaks
Memory allocated with malloc must eventually be returned to the operating system using free.
free(x);A memory leak occurs when a program allocates memory but loses the pointer to it or exits without freeing it.
For example:
int *x = malloc(10 * sizeof(int));
// x is never freedThe allocated memory remains marked as in use even if the program no longer needs it. Repeatedly leaking memory can cause a program or computer to:
Use increasing amounts of RAM.
Slow down.
Freeze.
Crash.
Memory should be freed only after the program has finished using it. Accessing memory after freeing it is also invalid:
free(x);
x[0] = 50; // Invalid: x points to freed memoryThe correct general order is:
Allocate memory.
Use the memory.
Free the memory when it is no longer needed.
Do not access it afterward.
Valgrind
Valgrind is a command-line tool that detects memory-management errors. It can identify problems even when a program appears to produce the correct output.
A program can be run under Valgrind by prefixing the command:
valgrind ./programValgrind can report:
Invalid reads.
Invalid writes.
Memory leaks.
The amount of memory leaked.
The source file and line number associated with an error.
The chain of function calls that led to the problem.
For example, an error such as “invalid read of size 4” indicates that the program tried to read four bytes from memory it was not permitted to access. Since an int commonly occupies four bytes, this often points to an invalid integer access.
Valgrind may also display messages such as:
“40 bytes in one block are definitely lost.”
“All heap blocks were freed.”
“No leaks are possible.”
The phrase “definitely lost” generally means that allocated memory can no longer be reached through any valid pointer and therefore cannot be freed by the program.
Combining Valgrind and help50
Valgrind’s output can be difficult to interpret. Running it through help50 can produce more accessible explanations:
help50 valgrind ./programThis can translate a technical message into guidance such as:
The program attempted to modify memory outside the bounds of an array.
The program leaked memory allocated by
malloc.A particular source-code line should be inspected.
Valgrind can also be used with command-line arguments. The arguments are passed normally after the executable name:
valgrind ./program argument1 argument2Handling allocation failure
malloc and realloc may fail if the computer cannot provide the requested memory. When allocation fails, these functions return NULL.
A robust program checks the result:
int *x = malloc(sizeof(int));
if (x == NULL)
{
return 1;
}The same principle applies to realloc. Its return value should usually be stored in a temporary pointer before replacing the original pointer:
int *tmp = realloc(x, new_size);
if (tmp == NULL)
{
free(x);
return 1;
}
x = tmp;This avoids losing the original pointer if reallocation fails.
The Organization of a Program’s Memory
A running program’s memory is divided conceptually into several regions.
Text segment
The text segment contains the machine code of the running program. When a program is launched:
Its code is stored long-term on a hard drive or solid-state drive.
The operating system loads the code into RAM.
The processor executes the code from memory.
RAM is faster than long-term storage because it is electronic and does not rely on moving mechanical parts.
Stack
The stack stores information associated with active function calls, including:
Local variables.
Function parameters.
Return information.
Individual function call frames.
For example:
mainreceives one region of stack memory.If
maincallsswap,swapreceives another region.If
swapcalls a third function, that function receives another region.
When a function returns, its stack frame is removed.
Heap
The heap is the region from which dynamic memory is allocated.
Functions associated with the heap include:
mallocreallocfree
Calling malloc marks part of the heap as being in use. Calling free marks that memory as available again. The physical memory does not disappear; the operating system changes how it tracks that region.
Stack and heap collision
The stack and heap share a finite amount of memory. If either grows too far, they may collide. This can produce serious errors, including stack overflow or failure to allocate more heap memory.
The central principle is that memory is limited. Programs must manage it carefully, especially when allocating large or dynamically growing structures.
Pointers and Passing Addresses
Values versus addresses
When a variable is passed to a function normally, the function receives a copy of its value.
Suppose main contains:
int x = 1;
int y = 2;If main calls:
swap(x, y);then swap receives copies of x and y. Its local variables may be named a and b, but changing them does not change the original x and y.
This occurs because each function has its own stack frame.
Passing pointers
To allow a function to modify variables owned by its caller, the caller passes their addresses:
swap(&x, &y);The function receives pointers:
void swap(int *a, int *b)The pointers act as addresses or “breadcrumbs” leading back to the original variables.
The function can then modify the original values by dereferencing the pointers:
int tmp = *a;
*a = *b;
*b = tmp;Here:
ais the address ofx.bis the address ofy.*ameans “go to the address stored ina.”*bmeans “go to the address stored inb.”
Dereferencing invalid pointers
A pointer must point to a valid memory location before it is dereferenced.
For example:
int *x;
int *y;
x = malloc(sizeof(int));
*y = 13; // Invalid if y was never initializedThe pointer y has not been assigned a valid address. It may contain an unpredictable garbage value, which is leftover bit patterns from previous uses of memory.
Dereferencing it may:
Crash the program.
Modify unrelated memory.
Appear to work accidentally.
Produce unpredictable behavior.
A pointer should never be dereferenced unless it has been explicitly initialized to:
A valid allocated address.
The address of an existing variable.
NULL, provided the program checks forNULLbefore dereferencing.
NULL represents an invalid or absent pointer. It is commonly represented numerically as zero, although programmers should treat it conceptually as a special pointer value rather than as an ordinary address.
Structures and User-Defined Data Types
C provides several primitive data types, such as:
charintfloatdoublelongBoolean values
A structure, or struct, allows a programmer to combine related values into one custom data type.
Defining a structure
A student could be represented using a structure containing a name and dormitory:
typedef struct
{
char *name;
char *dorm;
}
student;This defines a new type called student.
Each student contains:
A
char *calledname.A
char *calleddorm.
A char * represents the address of a character and is used to represent a string in C.
Accessing structure fields
If students is an array of student structures, an individual student’s fields can be accessed with the dot operator:
students[0].name
students[0].dormThe square brackets select an array element, and the dot selects a field within that structure.
Encapsulation
Encapsulation means grouping related data into one coherent structure.
Without structures, a program might use separate arrays:
char *names[enrollment];
char *dorms[enrollment];The program would have to remember that names[0] and dorms[0] belong to the same person. A structure keeps those related values together:
student students[enrollment];This improves:
Organization.
Readability.
Maintainability.
The ability to represent real-world concepts in code.
A student is an abstraction: a useful programming concept that hides the implementation details of the data. In this example, the abstraction consists of a name and a dormitory.
Header files
A header file, conventionally ending in .h, can contain definitions shared by multiple source files.
Programmers commonly include library headers such as:
#include <stdio.h>
#include <stdlib.h>A programmer can also create custom headers containing user-defined structures and declarations.
Arrays and Their Limitations
An array stores elements of the same data type in contiguous memory.
Advantages of arrays
Arrays provide:
Contiguous storage.
Fast access by index.
Constant-time random access.
If the address of the first element is known, the address of another element can be calculated arithmetically. Therefore, accessing an element at any valid index takes constant time:
Fixed size
The major limitation of a traditional C array is that its size is fixed after declaration.
int numbers[2];This creates space for exactly two integers. If a third integer is needed, the original array cannot simply be expanded.
The usual process is:
Allocate a larger array.
Copy all existing elements into it.
Add the new element.
Stop using or free the old array.
If the original array contains n elements, copying those elements takes:
Thus, resizing an array is a linear-time operation.
Homogeneous element types
An ordinary array stores elements of one type. For example:
An
intarray contains integers.A
chararray contains characters.A
studentarray contains students.
Although mechanisms involving void * can technically allow mixed types, doing so is usually less clear and less safe than designing an appropriate structure.
Wasted capacity
A programmer may allocate more space than is currently needed to avoid frequent resizing. This reduces the number of reallocations but wastes memory if much of the allocated capacity remains unused.
For example, an array with capacity 1,000 may contain only ten elements. The unused space is available but contributes no useful data.
Array design involves a trade-off between:
Time spent resizing.
Memory reserved but not currently used.
Dynamically Growing Arrays
A dynamically allocated array can grow while the program runs.
Size and capacity
Two values are useful for tracking a dynamic array:
Size: The number of elements currently stored.
Capacity: The number of elements the allocated memory can hold.
For example:
Size =3
Capacity =5
The array contains three elements and has room for two more.
realloc
The function realloc changes the size of an existing heap allocation.
Conceptually, it may work in either of two ways:
If enough memory is available immediately after the current block, the block may be extended in place.
If the adjacent memory is unavailable, a new larger block is allocated elsewhere, the old contents are copied, and the new address is returned.
The second case requires copying the existing elements and therefore takes linear time.
A simple growth operation might request space for one additional integer:
numbers = realloc(numbers, (size + 1) * sizeof(int));This approach is correct only if the return value is checked properly and if the original pointer is not lost when reallocation fails.
Growing by one element at a time
If the array is resized every time one new element is entered, the program may repeatedly copy its contents:
One element copied during the first expansion.
Two elements copied during the second.
Three elements copied during the third.
Continuing up to n elements.
The total work is approximately:
which is:
for inserting n elements one at a time under this strategy.
Allocating extra capacity
A more efficient strategy is to increase capacity by a larger amount, often by multiplying it by a constant factor. For example, capacity might grow from:
This does not eliminate reallocation, but it makes reallocations less frequent. The average cost of insertion can become close to constant time, although an individual expansion may still take linear time.
The best strategy depends on the application:
General-purpose computers usually have abundant memory, making modest over-allocation acceptable.
Resource-constrained devices may require careful memory conservation.
The goal is to choose an intentional balance between speed and memory use.
Ending input
A program that repeatedly asks for integers needs a way to detect that the user is finished.
If the input function only accepts integers, the user cannot enter a character such as q without causing an invalid input.
A common command-line convention is:
Control-C: Terminates the program.
Control-D: Signals end-of-file, or end of input, on many Unix-like systems.
A library may represent end-of-file using a special sentinel integer such as INT_MAX. A sentinel is a reserved value used to represent a special condition rather than ordinary data.
Linked Lists
A linked list stores elements in individually allocated nodes. Each node contains data and a pointer to the next node.
Node structure
A node storing an integer can be defined as:
typedef struct node
{
int number;
struct node *next;
}
node;Each node contains:
An integer field called
number.A pointer called
next.next, when non-NULL, stores the address of another node.
The repeated use of struct node is necessary because the structure refers to itself. This is called a self-referential structure.
The first occurrence tells C that a structure named node is being defined. The pointer field can then refer to another structure of the same type.
The first pointer
A linked list is accessed through a pointer to its first node, often called head or numbers.
node *numbers = NULL;If the list is empty, the pointer is NULL.
The first pointer is crucial because the rest of the list can be reached by following each node’s next pointer. If the first pointer is lost, the rest of the list becomes inaccessible even if the nodes still exist in memory.
Nodes need not be contiguous
Unlike an array, the nodes of a linked list do not need to be adjacent in memory.
A list might contain nodes at addresses such as:
100
150
475
Each node stores the address of the next node, allowing the program to follow the chain.
This makes linked lists dynamically expandable without copying all existing elements.
The NULL terminator
The next pointer of the final node is set to NULL.
This signals that:
The current node is the last node.
No further node exists.
Traversal should stop.
A linked list can therefore be visualized as:
first -> node -> node -> node -> NULLAllocating a node
A new node can be allocated dynamically:
node *n = malloc(sizeof(node));The result should be checked:
if (n == NULL)
{
return 1;
}After allocation, the node’s fields can be initialized:
n->number = 55;
n->next = NULL;The arrow operator
The arrow operator accesses a field through a pointer to a structure.
n->number
n->nextThe expression:
n->numberis shorthand for:
(*n).numberThe process is:
Dereference
nto reach the node.Access the
numberfield within that node.
The arrow operator is therefore syntactic shorthand, not a new memory operation.
Inserting at the beginning
Inserting a new node at the beginning of a linked list requires a small number of pointer changes:
Set the new node’s
nextpointer to the current first node.Update the list’s first pointer to point to the new node.
Conceptually:
n->next = numbers;
numbers = n;This takes constant time:
It does not matter how many nodes are already in the list.
Inserting at the end
To insert at the end while preserving the existing order, the program must traverse the list until it finds a node whose next field is NULL.
A traversal pointer can be initialized to the beginning:
for (node *ptr = numbers; ptr != NULL; ptr = ptr->next)
{
...
}The update expression:
ptr = ptr->nextmoves the pointer to the next node.
Once the final node is found:
ptr->next = n;The new node is attached to the end.
Finding the end requires visiting the nodes one by one. If the list contains n nodes, the operation takes:
A second pointer called last could store the final node, allowing insertion at the end in constant time. Maintaining such a pointer requires additional bookkeeping whenever nodes are added or removed.
Inserting in sorted order
To insert a node while preserving sorted order, the program must find the correct position.
The pointer updates must happen in the correct order. For inserting a node between two existing nodes:
Set the new node’s
nextpointer to the successor node.Set the predecessor’s
nextpointer to the new node.
If the predecessor pointer is changed first, the link to the successor may be lost.
For example:
n->next = current->next;
current->next = n;The new node must first preserve the remainder of the list before the predecessor is redirected.
Singly versus doubly linked lists
A singly linked list stores only a pointer to the next node. It can move forward but not backward.
A doubly linked list stores two pointers:
A pointer to the next node.
A pointer to the previous node.
Doubly linked lists make backward traversal easier, but each node requires additional memory and pointer updates.
Advantages of linked lists
Linked lists provide:
Dynamic growth.
No need to know the final size in advance.
Efficient insertion at the beginning.
No need to move existing elements when adding a new node.
Nodes that can be located anywhere in memory.
Disadvantages of linked lists
Linked lists also have important costs:
Elements are not available by index in constant time.
Finding the ith element requires following links from the beginning.
Searching is generally linear.
Each node requires additional memory for one or more pointers.
Memory allocation for many individual nodes can add overhead.
Pointer manipulation is more complex and more error-prone.
A linked list trades the array’s fast random access for flexible resizing and insertion.
Hash Tables
A hash table combines an array with linked lists to support faster searching on average.
Basic structure
A hash table consists of:
An array of buckets.
A linked list associated with each bucket.
The array provides fast access to a bucket. The linked list stores the items assigned to that bucket.
For names, an array might contain 26 buckets corresponding to the letters A through Z:
Bucket 0: names beginning with A.
Bucket 1: names beginning with B.
...
Bucket 25: names beginning with Z.
The array entries are pointers to linked lists rather than the names themselves.
Hash functions
A hash function takes an input and produces an output used to determine where the item belongs.
For example:
Input: a person’s name.
Operation: examine the first letter.
Output: a number from 0 to 25.
The function might map:
A to 0.
B to 1.
C to 2.
Z to 25.
A hash function should ideally distribute items evenly among the available buckets.
Searching a hash table
To find a name:
Apply the hash function to determine the bucket.
Jump directly to that array entry.
Traverse the linked list stored in that bucket.
With 26 reasonably balanced buckets, each linked list may contain approximately:
items when there are n total names.
The array lookup itself takes constant time:
The linked-list search depends on the bucket’s length.
Worst-case performance
A poorly distributed hash function can place every item in the same bucket. For example, if every name begins with the same letter, the hash table becomes one long linked list.
In that worst case, searching takes:
Thus, a hash table is not automatically constant-time in every situation.
With a good hash function and a reasonably balanced distribution, practical search can be much faster than searching one long list. Even though the asymptotic worst case remains linear, the actual wall-clock time may improve substantially.
Designing a better hash function
Using only the first letter may not distribute names evenly because some letters are more common than others.
Possible improvements include:
Using the first and second letters.
Using the last name instead of the first name.
Using several characters together.
Using a student ID number.
Using a birth date or another relevant attribute.
Increasing the number of buckets.
The design goal is to create approximately equal-length chains.
A hash function should balance:
Uniform distribution.
Computation speed.
Memory use.
The number of available buckets.
Hash-table trade-offs
Hash tables combine different advantages:
The array provides fast bucket selection.
Linked lists allow each bucket to grow dynamically.
The list lengths are shorter than one global list when the hash function distributes data well.
The price is additional memory and more complicated implementation.
Trees and Binary Search Trees
A tree is a hierarchical data structure composed of nodes connected by edges or pointers.
Tree terminology
Important terms include:
Root: The top node of the tree.
Child: A node directly below another node.
Parent: A node directly above another node.
Leaf: A node with no children.
Height: The number of levels or longest downward path.
A tree can represent relationships such as family ancestry, file systems, or ordered data.
Binary search tree
A binary search tree is a tree in which each node has at most two children:
A left child.
A right child.
The values obey an ordering rule:
Values in the left subtree are smaller than the current node.
Values in the right subtree are larger than the current node.
This property allows a search to eliminate half of the remaining possibilities at each step, assuming the tree is balanced.
Representing a tree node
A binary tree node can be represented as:
typedef struct node
{
int number;
struct node *left;
struct node *right;
}
node;Each node contains:
A stored integer.
A pointer to the left child.
A pointer to the right child.
A missing child is represented by NULL.
Searching a binary search tree
To search for a value:
Begin at the root.
Compare the target with the current node.
If they are equal, the value has been found.
If the target is smaller, move to the left child.
If the target is larger, move to the right child.
Continue until the value is found or a
NULLpointer is reached.
For example, if the current node contains 55 and the target is 66, the search moves right. If the next node contains 77, the search moves left.
Complexity
If the tree is balanced, each level eliminates approximately half of the remaining possibilities. Searching therefore takes:
where n is the number of nodes.
The height of a balanced binary search tree is approximately logn.
However, if values are inserted in an unfortunate order, the tree can become unbalanced and resemble a linked list. In that worst case, searching takes:
Thus, a binary search tree is efficient when its height remains small.
Arrays versus trees
Arrays provide fast random access but cannot grow naturally. Trees require pointer traversal but can grow dynamically.
A binary search tree combines:
Dynamic allocation through nodes and pointers.
Ordered searching through the binary-search property.
Potentially logarithmic search time.
Tries
A trie is a tree designed for storing sequences, especially strings. The name comes from “retrieval,” although it is pronounced like “try.”
Structure of a trie
Each trie node contains an array of pointers. For an English alphabet, each node might have 26 positions:
One position for A.
One position for B.
...
One position for Z.
Each pointer leads to the node representing the next character in a word.
Storing a word
To store a word such as BILLY:
Begin at the root node.
Follow the position for
B.Move to the node reached by that pointer.
Follow the position for
I.Continue for
L,L, andY.Mark the end of the word.
Each character corresponds to one level of the trie.
Words with common prefixes reuse nodes. For example, BOB and BILLY share the initial B node but branch afterward.
Marking complete words
A trie must distinguish between:
A path that represents a complete word.
A path that is only a prefix of a longer word.
For example, if both BOB and BOBBY are stored, the node representing the final B in BOB must indicate that a complete word ends there. The path may still continue to represent BOBBY.
This usually requires an additional Boolean field or marker in each node, such as:
bool is_word;Searching a trie
To search for a word:
Start at the root.
Follow the pointer corresponding to the first character.
Continue through one pointer per character.
If any required pointer is
NULL, the word is absent.After the final character, check whether the node is marked as the end of a complete word.
The search time depends primarily on the word’s length, not on the total number of stored words.
If a word has length L, the search takes approximately:
For a fixed maximum word length, this can be treated as constant time relative to the number of words:
Memory cost
Tries use significant memory because every node may contain a large array of pointers.
For an alphabet of 26 letters, even a node representing only one character reserves space for 26 possible next-character pointers. Much of that space may be unused.
Thus, tries trade:
Very fast lookup.
Large memory consumption.
This is an example of a fundamental design trade-off: using more memory can reduce running time.
Applications
Tries are useful for:
Spell checkers.
Autocomplete.
Dictionary lookup.
Prefix searching.
Word games.
Predictive text.
A spell checker can load a large dictionary into memory and quickly determine whether each typed word exists.
Comparing Major Data Structures
Arrays
Storage: Contiguous memory.
Access: Constant-time indexing, O(1).
Resizing: Expensive; copying may require O(n) time.
Memory overhead: Low.
Best use: Data with known or slowly changing size and frequent indexed access.
Linked lists
Storage: Individual nodes connected by pointers.
Access: Sequential; searching generally takes O(n).
Insertion at beginning: O(1).
Resizing: Natural and dynamic.
Memory overhead: Extra pointer per node.
Best use: Data that changes size frequently and requires frequent insertion or deletion.
Hash tables
Storage: An array of buckets containing linked lists.
Average search: Often close to constant time with a good hash function.
Worst-case search: O(n).
Memory overhead: Bucket array and linked-list pointers.
Best use: Fast lookup by key when a suitable hash function is available.
Binary search trees
Storage: Nodes with left and right pointers.
Balanced search: O(logn).
Worst-case search: O(n) if the tree becomes unbalanced.
Ordering: Supports organized traversal.
Best use: Dynamically changing ordered data.
Tries
Storage: A tree whose nodes contain arrays of pointers.
Search: Depends on key length, approximately O(L).
Memory overhead: Very high.
Best use: Fast string and prefix lookup.
Fundamental Design Trade-offs
No single data structure is best for every problem. Choosing a structure requires considering several competing goals.
Time versus memory
Arrays use relatively little extra memory but may require expensive resizing.
Linked lists resize easily but use extra pointer memory and lose constant-time indexing.
Hash tables use more memory to reduce average search time.
Tries use substantial memory to make string lookup depend on word length rather than dictionary size.
Flexibility versus simplicity
Arrays are conceptually simple and efficient for indexed access. Linked lists and trees are more flexible but require careful pointer management.
The more directly a program manages memory, the more responsibility the programmer assumes for:
Allocation.
Initialization.
Correct pointer updates.
Traversal.
Deallocation.
Error handling.
Worst-case versus practical performance
Asymptotic analysis describes how an algorithm behaves as input size grows, especially in the worst case.
Practical performance also depends on:
Constant factors.
Memory layout.
Cache behavior.
Input distribution.
The quality of a hash function.
The balance of a tree.
For example, dividing a list into 26 hash-table buckets may still be classified as linear in the worst case, but the actual search may be much faster if the data is evenly distributed.
The most effective designs consider both mathematical complexity and real-world behavior.
Central Lessons
Programs can appear to work while containing serious memory errors.
Valgrind detects invalid memory accesses and memory leaks.
Every successful allocation with
mallocorreallocshould eventually be matched withfree.A pointer stores an address; dereferencing a pointer accesses the value at that address.
A pointer must be initialized to a valid address before dereferencing.
Structures group related values into custom data types.
Arrays provide fast random access but have fixed size and require homogeneous elements.
Linked lists grow dynamically but require sequential traversal.
Hash tables combine arrays and linked lists to improve average lookup speed.
Binary search trees use ordering to support logarithmic search when balanced.
Tries use arrays inside tree nodes to provide extremely fast string lookup at the cost of substantial memory.
Effective programming involves deliberate trade-offs among correctness, speed, memory usage, and implementation complexity.

Ask anything
We've read this whole study set, so questions about it get the best answers.