1. Home
  2. Explore
  3. Computer Science
  4. CS50 Debugging Tools

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

CS50 Debugging Tools

Speaker 1Speaker 2

CS50 Debugging Tools

14:49
0:00-14:49
  1. Maria

    Welcome back to CS50. Today we are focusing on tools for finding bugs, memory management in C, and the data structures that become possible once we understand pointers and structs.

  2. Hope

    Let's begin with the tools. CS50 IDE adds several useful capabilities: debug50, which lets you pause at breakpoints, step through code, and inspect variables; check50, which runs tests to check whether your code is correct; and style50, which points out formatting issues so your code is easier to read.

  3. Maria

    And help50 is the tool to reach for when a compiler or command produces an error message you do not understand. You put help50 before the command, and it tries to translate that cryptic message into more helpful, teaching-fellow-style guidance.

  4. Hope

    Printf is still useful too. You can print variable values, mark whether execution reached a particular point, or place a print statement inside a loop to see when that loop runs. For a deeply nested loop, that can be quicker than stepping through every single iteration with a debugger.

  5. Maria

    But debug50 is more versatile when you want to walk through the program carefully. Set a breakpoint where the interesting behavior occurs, then inspect the variables and follow the execution from there.

  6. Hope

    The final major C debugging tool in this lecture is Valgrind. It helps detect memory problems, including invalid reads and writes and memory leaks. These problems can exist even when a program appears to work, because C sometimes lets you get lucky.

  7. Maria

    A memory leak happens when your program asks the operating system for memory with malloc but never gives that memory back with free. If that happens repeatedly, the computer may slow down, freeze, or crash because the program keeps claiming more memory.

  8. Hope

    Consider allocating space for ten integers. You need ten times sizeof(int) bytes, rather than hard-coding an assumption that every integer is four bytes. Malloc returns an address, so you store that result in an int pointer, such as int *x.

  9. Maria

    The memory malloc gives you is contiguous, meaning the integers are stored back-to-back like an array. You can use x[0] through x[9]. But x[10] is outside the allocated region, because the valid indexes stop at 9.

  10. Hope

    The dangerous part is that the program may still run when you access x[10]. C does not necessarily stop you immediately. You might receive a slightly larger chunk of memory than you requested, or that location might happen to be available. But the code is still wrong, and it may fail on another computer or under different conditions.

  11. Maria

    Running Valgrind before the program exposes the problem. It can report an invalid read or write, identify the file and line where it happened, and show the chain of functions that led there. Its output is verbose and technical, so help50 can make it easier to interpret.

  12. Hope

    After fixing the out-of-bounds access, Valgrind may still report that bytes are definitely lost. That means the program allocated memory but did not free it. The proper fix is to call free when you are finished using that memory.

  13. Maria

    Timing matters, though. You should not free memory and then continue using it. Free it when you are genuinely done with it, often near the end of the program. A clean Valgrind report says that all heap blocks were freed and that there are zero errors.

  14. Hope

    Valgrind works with command-line arguments just like the program normally does: place Valgrind before the executable and provide the arguments afterward. You can also combine tools, such as using help50 to help interpret Valgrind's output.

  15. Maria

    The memory itself does not disappear when you call free. The operating system marks those bytes as available again, returning them to the pool of memory that other programs or allocations can use.

  16. Hope

    This is why manual memory management is a responsibility. Arrays created normally can be handled automatically, but once you use malloc, realloc, and free, you must track what memory you own and when it should be released.

  17. Maria

    There is also a very human debugging technique called rubber duck debugging. You explain your program aloud, line by line, to a rubber duck or another object. Saying, 'On this line I allocate memory, and on the next line I use it this way,' can make an error suddenly obvious.

  18. Hope

    The point is not that the duck answers. The point is that speaking forces you to reason through the program step by step instead of staring at the same code and hoping the bug reveals itself.

  19. Maria

    Now let's connect this to the memory model. A running program uses different regions of memory. The text segment contains the machine code of the program, which is loaded from slower long-term storage into faster RAM so it can execute.

  20. Hope

    The stack stores function calls and local variables. When main calls another function, that function receives its own region of stack memory. The heap stores dynamically allocated memory requested with malloc. Calling free marks heap memory as available again.

  21. Maria

    The stack and heap both have limited space. If they grow toward each other far enough, one can collide with the other. More generally, finite memory means a program can eventually run out of room if it keeps allocating without releasing memory.

  22. Hope

    This memory model also explains why the first swap function failed. When main passed x and y to swap, the function received copies called a and b. Swapping those copies worked inside swap, but it did not change the original variables in main.

  23. Maria

    The corrected version passes the addresses of x and y instead. If x is stored at address 100 and y at address 104, swap receives those addresses as breadcrumbs to the original values. Dereferencing the pointers lets swap change the values in main's memory.

  24. Hope

    But a pointer must point to valid memory before you dereference it. In the Binky example, one pointer had been declared but never made to point to an allocated object. Dereferencing it meant trying to access an unknown or invalid address.

  25. Maria

    That unknown value may be called a garbage value. Memory contains leftover zeroes and ones from earlier activity, so an uninitialized pointer is not reliably null and is not safe to use. Never dereference a pointer unless you have properly assigned it a valid address.

  26. Hope

    Structs let us create our own data types by grouping related values. For example, a student structure could contain a char pointer for a student's name and another char pointer for the dorm. A typedef can give that structure the convenient type name student.

  27. Maria

    This is encapsulation: instead of maintaining separate arrays for names and dorms and remembering that position zero in each refers to the same person, you keep the related information together in one student object. The dot operator accesses fields, such as students[i].name or students[i].dorm.

  28. Hope

    Arrays are useful, but they have limitations. In C, the elements normally have one consistent type, and the array's size is fixed when it is created. If you have room for two integers and later need a third, you cannot simply place it beyond the array.

  29. Maria

    One solution is to allocate a larger array, copy the old values into it, add the new value, and stop using the old array. If the original array contains n elements, that copying takes linear time, or big O of n.

  30. Hope

    The realloc function can perform that process for you. It receives the existing memory address and the new size. If there is room beside the current allocation, it may expand it there. Otherwise, it can allocate a new region, copy the contents, and return the new address.

  31. Maria

    There is a trade-off. You can allocate extra space in advance and avoid frequent resizing, but unused memory is then wasted. Memory is often plentiful on modern computers, while small devices may make that waste more important. These are design decisions rather than one universal rule.

  32. Hope

    A different strategy is a linked list. Instead of requiring all values to be adjacent, allocate one node at a time wherever memory is available. Each node stores a value and a pointer to the next node.

  33. Maria

    In C, that node can be defined with a self-referential structure: an integer field such as n, and a node pointer called next. The pointer is written as node *next because it stores the address of another node.

  34. Hope

    The word node appears before the structure is fully defined so the compiler knows that struct node is a type being defined. The pointer is important: a node does not contain an entire node inside itself; it contains an address pointing to another node.

  35. Maria

    A linked list needs a pointer to its first node, often called first or numbers. From that first node, you follow the next pointers to reach every later node. The final node's next pointer is null, which marks the end.

  36. Hope

    Insertion requires careful ordering of pointer updates. To insert a new node between two existing nodes, first make the new node point to the old next node. Then update the previous node to point to the new node. If you update the previous pointer first, you can lose access to the rest of the list.

  37. Maria

    A linked list avoids resizing the entire structure, but it does not provide random access. In an array, because elements are contiguous, you can calculate the address of element two immediately. In a linked list, you must follow the chain from the beginning.

  38. Hope

    That makes sorted insertion linear in the worst case: you may need to inspect every node to find the correct position. But if you do not need the list sorted, you can insert a new node at the beginning in constant time, or big O of one.

  39. Maria

    You can also keep a pointer to the last node and insert at the end efficiently. Or you can add a second pointer to every node so each node points both forward and backward, creating a doubly linked list. The extra pointers use more memory but make some movement easier.

  40. Hope

    Let's compare three ways to collect numbers. A fixed-size array is simple but limits the user in advance. A dynamically resized array can grow, but reallocating one element at a time may be inefficient. A linked list grows one node at a time without copying the whole collection.

  41. Maria

    For a dynamically growing array, keep track of both size and capacity. Size is how many elements are currently stored; capacity is how many elements fit in the allocated memory. When size equals capacity, allocate more space before storing the next number.

  42. Hope

    You can represent an initially empty dynamic array with a null pointer, size zero, and capacity zero. Each time the user enters a number and there is no room, use realloc to increase the capacity, then store the number at the current size and increment size.

  43. Maria

    A robust program should check whether realloc or malloc returns null. That means the allocation failed, perhaps because the computer has no more available memory. The program should handle that failure rather than using an invalid pointer.

  44. Hope

    The lecture uses Control-D as an end-of-file signal to tell the program that the user has finished entering numbers. Control-C terminates the program, whereas Control-D signals the end of input. The CS50 library represents that condition with a special sentinel value such as INT_MAX.

  45. Maria

    After using a dynamic array, free it. Valgrind can reveal the consequence of forgetting: if three integers were allocated and each integer occupies four bytes, Valgrind can report that twelve bytes were lost. Adding free removes that leak.

  46. Hope

    For a linked-list implementation, malloc allocates space for one node, and the returned address is stored in a node pointer. If n is that pointer, n->number stores a value in the node's number field, and n->next accesses its next-pointer field.

  47. Maria

    The arrow operator is shorthand. Writing n->number is equivalent in meaning to (*n).number: follow the pointer to the node, then use dot notation to access the field. The arrow is simply clearer and more convenient.

  48. Hope

    To traverse a list, create a pointer such as ptr and initialize it to the first node. Continue while ptr is not null. If ptr->next is null, you have reached the end; otherwise, advance with ptr = ptr->next.

  49. Maria

    Once we can combine arrays, pointers, structs, and linked lists, we can build more advanced structures. One example is a hash table, which combines an array with linked lists.

  50. Hope

    Suppose you store names by their first letter. The array has 26 buckets, one for each letter. A hash function takes a name as input and returns a bucket number: A maps to one position, B to another, and so on.

  51. Maria

    Each bucket contains a linked list of names beginning with that letter. The array gives constant-time access to the appropriate bucket, while the linked list lets that bucket grow dynamically. If names are distributed reasonably evenly, each list is much shorter than one giant list.

  52. Hope

    In the worst case, a hash table can still take big O of n time if every item maps to the same bucket. A poor hash function can create that situation. In practice, a well-designed function spreads values across buckets, improving actual wall-clock performance even though the formal worst-case bound remains linear.

  53. Maria

    The choice of hash function and number of buckets matters. You might use more than the first letter, or use a last name, an identification number, or another property. The goal is to distribute the data as evenly as possible.

  54. Hope

    A tree is another structure built from nodes and pointers. Each node can contain a value and pointers to a left child and a right child. In a binary search tree, values to the left are smaller and values to the right are larger.

  55. Maria

    Searching a well-structured binary search tree resembles binary search. Start at the root, compare the target with the current value, then follow either the left or right pointer. If the tree is balanced, its height is logarithmic in the number of nodes, so the search takes about log n steps.

  56. Hope

    The tree structure avoids the fixed size of an array because nodes can be allocated dynamically. Its performance depends on its shape, though. The useful logarithmic behavior comes from a tree that stays reasonably balanced.

  57. Maria

    The final structure is a trie, pronounced like 'try.' A trie is a tree in which each node is effectively an array, often with one position for each letter. To store a word, follow a path corresponding to its characters.

  58. Hope

    For example, storing a word beginning with B follows the B position in the first array. The next character follows a position in the next array, and the process continues until the word is represented. Words with shared prefixes can reuse the same initial nodes.

  59. Maria

    A trie can find a word in a number of steps related to the word's length, not to the total number of words stored. That can behave like constant time when the maximum word length is treated as bounded. The price is memory: arrays at every node can consume a great deal of space.

  60. Hope

    If one word is a prefix of another, such as Bob and Bobby, the structure needs information indicating whether a word ends at that node or continues farther. The idea is that reaching a node does not automatically mean the complete word ends there.

  61. Maria

    These structures prepare us for implementing a spell checker. A spell checker loads a large dictionary into memory, then checks each word you type by looking it up and deciding whether to mark it as misspelled.

  62. Hope

    The broader lesson is that correctness and design are separate goals. Use check50 and sample inputs, but also use debug50, Valgrind, help50, printf, and even rubber duck debugging to expose problems. Then choose among arrays, dynamic arrays, linked lists, hash tables, trees, and tries based on the time and memory trade-offs your problem requires.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent