CS50 Debugging Tools
Memory Management and Data Structures in C
Development and Debugging Tools
Several tools help identify different classes of programming problems. Each tool provides a different kind of feedback, so effective debugging involves choosing the tool that matches the problem.
debug50
debug50 provides an interactive graphical debugger. It allows a programmer to:
Set breakpoints at specific lines.
Pause program execution.
Execute code 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.
A breakpoint can be placed deeper in a program when repeatedly stepping through earlier code would be tedious. This is especially useful for nested loops or functions that execute many times.
check50
check50 is an automated correctness checker. It runs a collection of tests against a program and reports whether the program behaves as expected.
It is useful because it:
Automates repetitive testing.
Checks multiple expected behaviors.
Provides feedback similar to what a teaching assistant might provide.
Can detect incorrect outputs even when a program appears to work for one manually selected input.
However, passing tests does not prove that a program has no memory errors. A program may produce the expected output while still reading or writing memory incorrectly.
printf
printf is useful not only for producing required output, but also for debugging. It can reveal:
The value of a variable at a particular moment.
Whether execution reached a particular line.
How many times a loop has executed.
Which branch of a conditional was taken.
Intermediate results in a long calculation.
For example, placing a printf statement inside a loop can show exactly when the loop executes. This may be more convenient than stepping through dozens of iterations with a debugger.
style50
style50 checks the formatting and style of C code. It can identify issues such as:
Incorrect indentation.
Inconsistent spacing.
Unnecessary or missing spaces.
Formatting that makes code harder to read.
Good style improves readability for both the original programmer and other programmers who may later maintain the code.
help50
help50 interprets difficult command-line error messages and provides more approachable explanations. It is particularly useful when:
Compilation fails.
A command produces a cryptic error.
The programmer does not yet recognize the meaning of a compiler or terminal message.
It can be placed before a command, such as a compilation command, to provide additional guidance.
A general debugging strategy
A programmer should use tools instead of relying only on repeatedly staring at the source code. A useful general approach is:
Use
printffor quick observations about values or control flow.Use
debug50to step through important sections and inspect variables.Use
check50to test expected behavior.Use
style50to improve readability.Use
help50when an error message is unclear.Use
valgrindto find invalid memory operations and memory leaks.Explain the program step by step, either to another person or through rubber duck debugging.
Memory Errors and valgrind
C gives programmers direct access to memory. This power makes C flexible and efficient, but it also creates responsibilities. A program can contain serious memory errors even when it appears to run correctly.
Segmentation faults
A segmentation fault occurs when a program accesses memory that it is not allowed to access. Common causes include:
Reading beyond the end of an array.
Writing beyond the end of an array.
Dereferencing an invalid pointer.
Dereferencing a pointer that was never initialized.
Accessing memory after it has been freed.
A segmentation fault is not the only possible result of an invalid memory operation. Sometimes the program crashes, but sometimes it appears to work because the computer happens to permit the access. This makes memory bugs especially difficult to detect.
Undefined behavior
Accessing memory outside the region allocated to a program produces undefined behavior. The C language does not guarantee what will happen. Possible outcomes include:
The expected value appears.
A wrong value appears.
The program crashes.
Other variables are silently corrupted.
The program works on one computer but fails on another.
The bug appears only under certain inputs or operating-system conditions.
For example, if a program allocates space for 10 integers, valid indexes are:
Accessing index 10 is invalid, even if the program happens to print a plausible value.
Why an invalid access may appear to work
Operating systems and memory allocators may provide a block of memory that is larger than the exact amount requested. This can happen for performance or organizational reasons. As a result, an out-of-bounds access may land in memory that is physically available, even though the program does not own it.
This apparent success is accidental. Another computer may arrange memory differently, causing the same code to fail. Therefore, successful output is not sufficient evidence that memory use is correct.
What valgrind does
valgrind is a command-line tool that detects memory-related problems while a program runs. It can identify:
Invalid reads.
Invalid writes.
Reads or writes of a particular number of bytes.
The source line where an invalid access occurs.
The chain of function calls that led to the error.
Memory allocated with
mallocbut never released withfree.
A typical command has the form:
valgrind ./programIf the program requires command-line arguments, those arguments are supplied normally after the program name. help50 can also be used with valgrind to make its output easier to understand.
Interpreting common valgrind messages
Invalid read
An invalid read means that the program attempted to retrieve data from memory outside the valid region.
For example, reading an integer usually involves reading 4 bytes on many systems. A message such as “invalid read of size 4” indicates that the program tried to read an integer from an invalid location.
Invalid write
An invalid write means that the program attempted to store data in memory outside the valid region.
Writing an integer often involves writing 4 bytes, so “invalid write of size 4” commonly indicates that an integer was written beyond an array’s boundary.
Definitely lost
A message stating that bytes are “definitely lost” indicates a memory leak. The program allocated memory but no longer has a pointer through which it can free that memory.
For example, if a program allocates space for 3 integers and each integer occupies 4 bytes, then failing to free that memory produces a leak of:
A successful final report should indicate that all heap blocks were freed and that no leaks are possible.
Dynamic Memory: malloc, free, and realloc
malloc
malloc allocates a requested number of bytes on the heap. It returns the address of the allocated block.
Because the result is an address, it must usually be stored in a pointer. For example, space for 10 integers can be requested with an amount based on sizeof:
int *x = malloc(10 * sizeof(int));This requests enough space for 10 values of type int, regardless of how many bytes an int occupies on a particular computer.
Using sizeof(int) is safer than assuming that an integer always occupies 4 bytes.
The return value of malloc
If allocation succeeds, malloc returns a valid address. If allocation fails, it returns NULL.
A robust program checks for failure:
int *x = malloc(10 * sizeof(int));
if (x == NULL)
{
return 1;
}The condition can also be written as:
if (!x)
{
return 1;
}A program should not dereference a pointer when allocation failed.
free
Memory obtained with malloc must eventually be returned to the operating system using free:
free(x);Calling free communicates that the program no longer needs that heap memory. The memory does not disappear physically; instead, the operating system marks it as available for future allocation.
A program that allocates memory without freeing it creates a memory leak. Repeated leaks can cause a computer to slow down, freeze, or crash.
Correct timing of free
Memory should be freed only when the program is finished using it. Freeing memory too early creates another error:
free(x);
printf("%i\n", x[0]); // Invalid: x is no longer usableAfter free(x), the pointer should not be dereferenced. The data may still appear to be present, but accessing it produces undefined behavior.
realloc
realloc changes the size of an existing heap allocation. It can be used to grow or shrink dynamically allocated memory.
Conceptually, realloc may work in either of two ways:
If sufficient space is available immediately after the current block, the block may grow in place.
If nearby space is unavailable, a larger block may be allocated elsewhere, the original data may be copied, and the new address may be returned.
Because the new block may have a different address, the return value of realloc must be handled carefully.
A safer pattern is:
int *temporary = realloc(numbers, new_size);
if (temporary == NULL)
{
free(numbers);
return 1;
}
numbers = temporary;Storing the result in a temporary pointer prevents the original pointer from being lost if realloc fails.
Uninitialized memory
Newly allocated memory is not automatically cleared. Its contents may contain leftover bits from previous uses of that region of memory. These unknown contents are called garbage values.
A program must initialize allocated memory before relying on its contents.
The Organization of a Program’s Memory
A running C program’s memory can be viewed as several regions.
Text segment
The text segment contains the machine instructions of the running program. When a program is launched, its executable instructions are loaded from long-term storage into RAM so that the processor can execute them efficiently.
Stack
The stack stores function-related data, including:
Local variables.
Function parameters.
Return information.
Individual function call frames.
When main calls another function, the called function receives its own stack frame. If that function calls another function, another frame is placed on the stack.
Stack frames are temporary and generally exist only while the corresponding function is executing.
Heap
The heap is the region used for dynamically allocated memory. Functions such as malloc, realloc, and free operate on heap memory.
Heap memory remains allocated until it is explicitly freed or until the program terminates.
Stack and heap limitations
The stack and heap share a finite amount of memory. If a program uses too much stack space or heap space, the regions can collide or the operating system can refuse additional allocation.
Potential causes include:
Excessive recursion, which can overflow the stack.
Repeated allocation without freeing, which can exhaust the heap.
Requesting more memory than the computer can provide.
Pointers and Dereferencing
A pointer is a variable that stores a memory address.
For example:
int *p;This declares p as a pointer to an integer. It does not itself allocate an integer or guarantee that p points to valid memory.
Dereferencing
The * operator can be used to dereference a pointer. Dereferencing means following the stored address and accessing the data located there.
If p contains the address of an integer, then:
*p = 13;stores the value 13 at that address.
A pointer must be initialized to a valid address before it is dereferenced.
Invalid pointers
A pointer that has been declared but not initialized contains an unpredictable value. It may point anywhere in memory. Dereferencing it can therefore read or modify unrelated memory.
A pointer initialized to NULL is also not dereferenceable. NULL represents the absence of a valid address. It is commonly used to indicate that:
No memory has been allocated.
A linked list has reached its end.
An allocation failed.
A pointer does not currently refer to an object.
Pointer values and addresses
A pointer may contain a numerical address such as 100 or 475. The exact numerical value is usually not important to the programmer. What matters is that the address leads to the intended data.
Pointers can be viewed as breadcrumbs that allow code to locate data stored elsewhere in memory.
Passing Values and Pointers to Functions
C passes function arguments by value. This means that a function receives a copy of each argument.
Suppose main contains two integers, x and y, and calls a function that accepts two integer parameters, a and b. The function receives copies:
ainitially contains the value ofx.binitially contains the value ofy.
If the function swaps a and b, it swaps only the copies. The original x and y remain unchanged.
Swapping through pointers
To modify the original variables, the function must receive their addresses:
void swap(int *a, int *b)
{
int temporary = *a;
*a = *b;
*b = temporary;
}A call might look like:
swap(&x, &y);Here:
&xmeans the address ofx.&ymeans the address ofy.aandbstore those addresses.*aand*baccess the original variables.
Pointers allow one function to modify data that belongs to another function.
Structures and User-Defined Types
C provides several primitive data types, but real-world entities often require multiple related values. A structure, declared with struct, groups related fields into a single data type.
For example, a student could be represented with:
typedef struct
{
char *name;
char *dorm;
}
student;This creates a custom type called student, with two fields:
name, a pointer to characters.dorm, a pointer to characters.
Encapsulation
Grouping related data into one structure is called encapsulation. Instead of maintaining separate arrays for names, dormitories, phone numbers, and other information, a program can store all information about one student together.
A student is therefore an abstraction: a convenient programming concept that represents several underlying values.
Accessing structure fields
If students is an array of student structures, then an individual student’s fields can be accessed using:
students[i].name
students[i].dormThe square brackets select an array element, and the dot selects a field within that structure.
Header files
A programmer can place a custom structure definition in a header file, such as a file ending in .h. Header files commonly contain declarations or definitions intended to be shared across multiple source files.
Arrays and Their Limitations
An array stores elements in a contiguous region of memory. If an array begins at address A and each element occupies k bytes, the address of element i can be calculated as:
This calculation gives arrays efficient random access.
Advantages of arrays
Elements are stored next to one another.
The address of any element can be calculated directly.
Accessing an element by index takes constant time, O(1).
Arrays are generally memory-efficient and simple to traverse.
Limitations of arrays
Fixed capacity
An ordinary C array has a fixed size. If an array is declared with space for 2 elements, a third element cannot simply be appended.
To enlarge it, a program must:
Allocate a new, larger array.
Copy all existing elements.
Add the new element.
Release the old array.
If the original array contains n elements, copying them requires O(n) time.
Over-allocation
A program can allocate a large array in advance to avoid repeated resizing. However, unused space is wasted. Choosing too small a capacity leads to resizing; choosing too large a capacity wastes memory.
Homogeneous element types
An ordinary array stores elements of one declared type. An array can contain all integers, all characters, or all structures of one type, but it does not ordinarily mix unrelated types.
Dynamically Resizing an Array
A dynamically allocated array can be represented by a pointer:
int *numbers = NULL;Initially, the pointer does not refer to an array. The program can later use malloc or realloc to allocate the required space.
Two variables are useful:
Size: the number of elements currently stored.
Capacity: the number of elements for which memory has been allocated.
The relationship is:
When size == capacity, the array has no unused space. The program must allocate more memory before storing another element.
Incremental resizing
A simple strategy is to increase capacity by one whenever the array becomes full. Although easy to understand, this can be inefficient because every insertion may copy all existing elements.
If the array grows from n to n+1 elements repeatedly, the total copying can become much larger than O(n) over the entire sequence of insertions.
Larger growth increments
Another strategy is to increase capacity by a larger amount, such as a fixed block or a multiplicative factor. This reduces the number of reallocations but may use additional memory.
The choice involves a trade-off:
More allocated space can improve speed.
Less allocated space can reduce memory use.
The best choice depends on the application and the available resources.
End-of-input signaling
A dynamically growing input loop needs a way for the user to indicate that no more numbers will be entered.
Using getInt prevents the user from entering a non-integer command such as q, because getInt expects an integer. A program could instead use string input and convert valid strings to integers, but that would require additional parsing.
A common command-line convention is:
Control-D: signals end-of-file, or end of input.
Control-C: terminates the running program.
The input function may use a special sentinel value to represent end-of-file. A sentinel is a reserved value that signals a special condition rather than ordinary user data.
Linked Lists
A linked list stores elements in separate nodes. Each node contains:
A data value.
A pointer to the next node.
A basic node can be defined as:
typedef struct node
{
int number;
struct node *next;
}
node;Each node therefore has the conceptual form:
[number | pointer to next node]The nodes do not need to be adjacent in memory.
Why the structure refers to itself
The field next points to another object of type struct node. The structure definition uses the name struct node before the type alias node has been completed.
The initial struct node in the definition informs the compiler that a structure with that name is being declared. The pointer is essential: a node does not contain another complete node directly; it contains only an address pointing to another node.
If a structure directly contained another complete instance of itself, its size would be infinite. A pointer has a fixed size, so self-referential pointers are valid.
The beginning and end of a list
A linked list is typically accessed through a pointer called head, first, or another similar name. This pointer stores the address of the first node.
The final node’s next field contains NULL, indicating that there is no subsequent node.
The list can therefore be traversed by following pointers:
head → node → node → node → NULLOnly the pointer to the first node must be remembered. Every later node can be reached by following the chain.
Advantages of linked lists
The list can grow dynamically.
Nodes do not need to be stored contiguously.
Inserting a node does not require shifting all later elements.
The list does not need a predetermined maximum size.
A program allocates only as many nodes as it needs.
Disadvantages of linked lists
Nodes require extra memory for pointer fields.
Elements do not support constant-time random access.
Finding the element at a particular position requires traversal.
Poor pointer management can cause leaks or disconnected portions of the list.
Nodes may be scattered throughout memory, reducing cache efficiency.
Inserting into a Linked List
Inserting at the beginning
If ordering does not matter, insertion at the beginning is especially efficient.
For a new node n and a list pointer head:
Set
n->nextto the currenthead.Set
headton.
Conceptually:
Before:
head → A → B → C → NULL
After inserting N:
head → N → A → B → C → NULLThis requires a constant number of pointer assignments, so the running time is:
Inserting at the end
To insert at the end while maintaining only a pointer to the first node, the program must traverse the list until it finds a node whose next field is NULL.
For a list of n nodes, this requires:
A second pointer called tail can track the final node. With both head and tail, insertion at the end can be reduced to O(1), provided that the tail pointer is updated correctly.
Inserting in sorted order
To insert a value while preserving ascending order, the program must find the correct position. This may require examining many nodes.
The general process is:
Begin at the first node.
Compare the new value with the current node and the next node.
Stop when the new value belongs between two nodes.
Set the new node’s
nextpointer to the following node.Set the preceding node’s
nextpointer to the new node.
The order of pointer updates matters. The new node must first point to the existing successor before the predecessor is redirected. Otherwise, the remainder of the list may become unreachable.
For example, given:
A → BTo insert N between them:
Set
N->next = B.Set
A->next = N.
The result is:
A → N → BLinked-list traversal
A traversal pointer can move from one node to the next:
for (node *ptr = head; ptr != NULL; ptr = ptr->next)
{
// Use ptr->number
}The update expression ptr = ptr->next means:
Follow the current node’s
nextpointer.Store that address in
ptr.Continue with the next node.
This is pointer arithmetic in a structural rather than numerical form: instead of adding a fixed offset to reach the next array element, the program follows an explicitly stored address.
The Arrow Operator
When a variable is a structure itself, the dot operator accesses a field:
student.nameWhen a variable is a pointer to a structure, the arrow operator accesses a field through that pointer:
n->number
n->nextThe arrow operator is shorthand for dereferencing first and then using dot notation:
(*n).number
(*n).nextThus:
nis a pointer to a node.*nis the node located at that address.n->numberaccesses the node’snumberfield.n->nextaccesses the node’snextpointer.
The arrow notation is especially useful for linked lists and trees because the program usually stores pointers to structures rather than structures directly.
Hash Tables
A hash table combines an array with linked lists. It is designed to provide faster lookup than one long list while retaining the ability to store a dynamically changing number of elements.
The basic idea
A hash table contains an array of buckets. Each bucket points to a linked list.
For example, a table for names might contain 26 buckets, one for each letter of the alphabet:
bucket 0 → names beginning with A
bucket 1 → names beginning with B
...
bucket 25 → names beginning with ZThe linked lists contain the actual data.
Hash functions
A hash function takes an input and produces an output that identifies a bucket.
For a simple name-based hash function:
Take a name as input.
Examine its first letter.
Map
Ato bucket 0,Bto bucket 1, and so forth.Insert the name into the linked list at that bucket.
The quality of the hash function matters. A good hash function distributes values relatively evenly across the buckets.
Why hash tables improve lookup
With one unsorted list containing n names, lookup may require:
With a hash table using 26 approximately equal buckets, the average list length is roughly:
The array provides rapid access to the appropriate bucket, and the linked list within that bucket is shorter than one list containing every name.
Worst-case behavior
A hash table can still have worst-case lookup time of:
This occurs when many or all values map to the same bucket. For example, if every name begins with the same letter, the hash table effectively becomes one long linked list.
Therefore, a hash table’s practical efficiency depends on:
The number of buckets.
The quality of the hash function.
The distribution of input data.
Whether collisions are common.
Collisions
A collision occurs when two or more inputs produce the same bucket number. Linked lists within buckets provide a way to store all colliding values.
The goal is not necessarily to eliminate collisions completely, but to distribute them so that each linked list remains reasonably short.
Choosing a hash function
A hash function could use:
The first letter of a first name.
Several letters of a name.
A last name.
A student ID digit.
A birth year.
Some combination of multiple properties.
Using more information can create more buckets and improve distribution, but it may also require more memory or computation.
A good design attempts to balance:
Uniform distribution.
Fast computation.
Reasonable memory use.
The characteristics of the expected data.
Trees and Binary Search Trees
A tree is a hierarchical data structure composed of nodes connected by pointers. A node may have children, which are nodes below it.
The top node is called the root. Nodes below another node are its children, and nodes below those children are descendants.
Binary trees
A binary tree allows each node to have at most two children:
A left child.
A right child.
A node can be represented as:
typedef struct node
{
int number;
struct node *left;
struct node *right;
}
node;Each node contains:
A value.
A pointer to a left child.
A pointer to a right child.
A missing child is represented by NULL.
Binary search tree property
A binary search tree is organized according to this rule:
Every value in the left subtree is smaller than the node’s value.
Every value in the right subtree is larger than the node’s value.
This property allows the tree to support divide-and-conquer searching.
Searching a binary search tree
To find a target value:
Start at the root.
Compare the target with the current node’s value.
If they are equal, the value has been found.
If the target is smaller, follow the left pointer.
If the target is larger, follow the right pointer.
Repeat until the value is found or the pointer becomes
NULL.
At each step, an entire subtree can be discarded.
Running time
If the tree is balanced, its height is approximately:
Therefore, search can take:
This resembles binary search in a sorted array, but a binary search tree can grow dynamically without shifting every element when a new node is added.
The importance of balance
The O(logn) performance assumes that the tree is reasonably balanced. If values are inserted in an unfortunate order, the tree may become skewed:
A → B → C → D → EIn that case, each node may have only one child, and the tree behaves like a linked list. The worst-case search time becomes:
Thus, the shape of the tree is crucial to its performance.
Tries
A trie is a tree used to store strings. The name is associated with retrieval and is pronounced like “try.”
Each node in a trie contains an array of pointers, with one pointer for each possible next character. For a simple English-language trie, a node might have 26 pointers corresponding to A through Z.
Storing a word
To store a word:
Begin at the root node.
Use the first character to select an array position.
Follow or create the pointer at that position.
Use the second character to select a position in the next node.
Continue until every character has been processed.
Mark the final node as indicating the end of a complete word.
For example, storing a word such as BILLY follows a path through nodes corresponding to:
B → I → L → L → YEach node along the path is itself an array of pointers.
Prefix sharing
Words with common prefixes reuse nodes. For example, BOB and another word beginning with BO can share the nodes representing B and O, then branch at later letters.
This sharing can reduce some duplication, although tries can still use substantial memory.
Marking complete words
A trie must distinguish between:
A path that is merely a prefix.
A path that represents a complete word.
For example, if both BOB and BOBBY are stored, the node representing the end of BOB must indicate that a word ends there, even though another path continues to BOBBY.
A separate Boolean flag or equivalent field can record whether a node marks the end of a complete word.
Lookup time
If the target word has length L, lookup requires approximately one step per character:
For a fixed maximum word length, this is often treated as constant time, O(1) with respect to the number of stored words.
For example:
A three-letter word requires approximately 3 character transitions.
A five-letter word requires approximately 5 transitions.
The number of other words in the trie does not directly determine the lookup path length.
Space-time trade-off
Tries use more memory than simple lists because each node may contain a large array of pointers. For an alphabet of size 26, every node may reserve space for 26 possible transitions, even when many are unused.
The primary trade-off is:
Advantage: Extremely fast lookup based on word length.
Disadvantage: High memory usage.
Tries are useful when fast string lookup is more important than minimizing memory consumption.
Comparing Major Data Structures
Array
Organization: Contiguous elements.
Access: Random access in O(1).
Growth: Fixed size unless copied or reallocated.
Insertion: Expensive in the middle or when resizing.
Memory use: Relatively efficient.
Linked list
Organization: Separate nodes connected by pointers.
Access: Sequential traversal, generally O(n).
Growth: Naturally dynamic.
Insertion: O(1) when the insertion location is already known.
Memory use: Extra pointer storage per node.
Hash table
Organization: Array of linked-list buckets.
Access: Average lookup can be close to constant time.
Worst case: O(n) if many values collide.
Growth: Can be expanded by resizing the bucket array.
Memory use: Requires bucket space and linked-list pointers.
Binary search tree
Organization: Nodes with left and right child pointers.
Access: O(logn) when balanced.
Worst case: O(n) when unbalanced.
Growth: Dynamic insertion.
Memory use: Two child pointers per node.
Trie
Organization: Tree of arrays indexed by characters.
Access: Approximately O(L) for a word of length L.
Dependence: Lookup depends primarily on word length, not the number of stored words.
Growth: Dynamic, with many pointer arrays.
Memory use: High, but lookup is very fast.
Spell Checkers and Practical Applications
A spell checker maintains a dictionary of valid words and tests words against that dictionary.
A typical spell-checking process is:
Load a large dictionary into memory.
Store the words in a chosen data structure.
Read words from a document.
Look up each word in the dictionary.
Mark words that are not found as misspelled.
Measure lookup time and memory use.
Possible dictionary structures include:
A simple array of words.
A sorted array with binary search.
A linked list.
A hash table.
A trie.
The choice affects:
Loading speed.
Lookup speed.
Memory consumption.
Implementation complexity.
Behavior for very large dictionaries.
The underlying purpose of these structures is to make it possible to handle large collections of data efficiently. Arrays, pointers, structures, dynamic memory, linked lists, hash tables, trees, and tries are reusable building blocks that can be combined according to the requirements of a problem.
Efficient programming requires balancing correctness, execution time, memory use, and implementation complexity. No single data structure is optimal for every situation.

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