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

15:12
0:00-15:12
  1. Hope

    Welcome back to our CS50 study session. Today we are focusing on debugging tools, memory, pointers, structs, and the data structures that grow out of those ideas. Let’s begin with the tools from CS50 IDE, because knowing how to investigate a problem is just as important as writing the code.

  2. Maria

    The debugger is debug50. It opens a panel where you can pause at breakpoints, step through a program one line at a time, and inspect variables as the program runs. Check50 is different: it automates tests of your program’s correctness, much like the tests teaching fellows might use when giving feedback.

  3. Hope

    And printf is still extremely useful. You can print variable values, confirm that execution reached a particular point, or place a print inside a nested loop to see how often the loop runs. Sometimes repeatedly clicking through a debugger would be tedious, so one strategically placed printf gives you the information you need.

  4. Maria

    Style50 checks formatting and readability, showing places where spaces should be added or removed. Help50 is the tool to reach for when a compiler or command gives you an error message that you do not understand. It tries to translate that cryptic output into more helpful, teaching-fellow-style guidance.

  5. Hope

    There is also a useful problem-solving technique called rubber duck debugging. You explain your code aloud, line by line, to a rubber duck or any listener that does not even have to answer. Often, hearing yourself say, “Now I allocate this, and then I use it here,” reveals the mistake immediately.

  6. Maria

    The major new command-line tool is Valgrind. It helps detect memory problems, especially memory leaks and invalid reads or writes. These bugs can exist even when a program appears to work, because C may let you get lucky instead of immediately reporting that you accessed memory incorrectly.

  7. Hope

    A memory leak happens when a program asks the operating system for memory with malloc but never returns it with free. If that continues repeatedly, the computer may slow down, freeze, or crash because available memory is being consumed without being released.

  8. Maria

    Consider allocating space for ten integers. Malloc returns the address of a contiguous block of memory, so you can treat that block like an array. The valid indexes are zero through nine. Writing to index ten is out of bounds, even if the program seems to run normally.

  9. Hope

    That apparent success is dangerous. The computer may have given you a chunk slightly larger than the ten integers you requested, or the memory beyond the array may happen not to cause an immediate failure. But another computer, another operating-system state, or a different run could behave differently. That is why code that works on one machine can fail on another.

  10. Maria

    Running Valgrind before the program reports an invalid read or write and identifies the file and line where the suspicious access occurred. Its raw output can be intimidating, with addresses and hexadecimal values, but help50 can make it more understandable by explaining that you may be modifying memory beyond an array’s bounds.

  11. Hope

    After fixing the out-of-bounds access, Valgrind may still report that bytes were definitely lost. That indicates a leak: memory was allocated but not freed. The fix is to call free when you are finished with the block, normally near the end of the program.

  12. Maria

    The order matters. You must not free a block and then continue using it. Free means you are telling the operating system that you no longer need that memory, so accessing it afterward is invalid. Once the program stops using the block, free it, and Valgrind should report that all heap blocks were freed and that there are zero errors.

  13. Hope

    Valgrind also works with command-line arguments. You run the program as usual, including its arguments, but put Valgrind before the command. The larger lesson is not to rely only on sample inputs or on staring at the screen. Use debugging, testing, memory-checking, and explanatory tools to gather evidence about what your program is doing.

  14. Maria

    Let’s connect this to the computer’s memory layout. When a program runs, its machine code is loaded into the text segment, because the computer needs quick access to those instructions in RAM. The heap is where dynamically allocated memory from malloc comes from, while the stack stores function calls and local variables.

  15. Hope

    When main calls another function, that function gets its own region on the stack. If it calls another function, another region is added. The heap and stack both occupy a finite amount of memory, so if either grows too far, they can collide. That is the basic idea behind a stack overflow or other out-of-memory failure.

  16. Maria

    The operating system keeps track of which memory locations are currently in use and which have been returned to the free list. Calling free does not erase the physical memory or make it disappear. It marks that region as available for future use.

  17. Hope

    This also explains why uninitialized pointers are dangerous. Declaring a pointer does not automatically make it point to valid memory. It may contain a garbage value left over from earlier activity in memory. Dereferencing that pointer—using the star operator to go to its supposed address—could crash, or could appear to work by luck.

  18. Maria

    A pointer should be dereferenced only after you have assigned it a valid address, such as the address returned by malloc, or a known address of an existing variable. Null is a special value that means the pointer does not point to a valid object. But unless you explicitly set a pointer to null, you should not assume an uninitialized pointer contains null.

  19. Hope

    That distinction is central to the swap example. A basic swap function received copies of two values. It successfully exchanged the copies inside the function, but the original variables in main were unchanged because each function has its own local memory.

  20. Maria

    The corrected version passes pointers to the original variables instead. If x is stored at address 100 and y at address 104, the function receives 100 and 104 rather than merely receiving the values stored there. Dereferencing those addresses lets the function change the original values in main.

  21. Hope

    That is why pointers are useful: they act like breadcrumbs to data stored elsewhere. The pointer itself contains an address, while the star operator follows that address to access the data at that location.

  22. Maria

    Structs build on this ability to group related data. With a custom student type, for example, you can store a char pointer for a name and another char pointer for a dorm. Instead of maintaining separate arrays and remembering that name zero belongs with dorm zero, one student structure encapsulates both pieces of information.

  23. Hope

    A header file can contain a definition like that so the custom type can be shared across programs. The dot operator accesses a field of a structure, so if students is an array of students, students[i].name refers to the name field of the element at index i.

  24. Maria

    This is called encapsulation: related information is kept together under one useful abstraction. In code, a student is not every fact about a real student. It is the particular set of fields the structure defines, such as a name and a dorm.

  25. Hope

    Arrays are useful, but they have limitations. Every element has the same data type, and the array’s size is fixed when it is created. If you allocate space for two integers and later need a third, you cannot simply place the third one beyond the original boundary.

  26. Maria

    You can allocate a new, larger array, copy the old values into it, add the new value, and stop using the old array. But copying n existing values takes linear time, or big O of n. The same basic issue applies when realloc has to move a block because there is no room immediately after it.

  27. Hope

    Realloc can sometimes extend a block in place if the following memory is available. Otherwise, it allocates a larger block elsewhere, copies the existing contents, and returns the new address. Either way, the operation may require linear work, and realloc operates on heap memory.

  28. Maria

    A linked list avoids deciding the total size in advance. Instead of one contiguous block, each node can be allocated separately. A node stores a value and a pointer to the next node, so the nodes can live in completely different places in memory while still being connected.

  29. Hope

    In C, a node can be defined with a self-referential structure: an integer field such as n, and a field called next whose type is node star. The first appearance of struct node tells the compiler that this structure name exists, and the pointer is allowed to refer to another node of the same type.

  30. Maria

    The final node’s next pointer is null, marking the end of the list. A separate pointer, often called first or numbers, stores the address of the first node. From that first node, you follow next pointers to reach every later node.

  31. Hope

    Inserting into a sorted linked list requires careful pointer updates. To insert a value in the middle, the new node must first point to the node that currently follows the insertion position. Only then should the previous node’s next pointer be changed to point to the new node.

  32. Maria

    If you change the previous pointer too early, you can lose access to the rest of the list. This is why the order of pointer assignments matters. A singly linked list also cannot move backward, so if you pass the correct insertion point, you may need to start again from the beginning.

  33. Hope

    Sorted insertion is big O of n in the worst case because you may need to walk through the entire list. But if order does not matter, insertion at the front takes constant time, or big O of one: point the new node at the current first node, then update the first pointer to the new node.

  34. Maria

    That illustrates a trade-off. Arrays offer fast random access because elements are contiguous, but resizing is costly. Linked lists grow naturally and do not require contiguous memory, but reaching a particular element requires following pointers one by one.

  35. Hope

    The list examples also show two ways to let users enter an unknown number of values. One approach uses a dynamically resized array. The program tracks size, meaning how many values are currently stored, and capacity, meaning how many values fit. When size equals capacity, it uses realloc to make room for one more value.

  36. Maria

    The program can continue in a loop until the user signals that input is finished. With the CS50 getInt function, the user cannot simply type a letter like q because getInt expects an integer. Control-D sends an end-of-file signal, which the library represents using a special sentinel value, often called INT_MAX.

  37. Hope

    A different interface could use getString and allow the user to type a command such as quit, but then the program would need to convert numeric strings into integers and compare the quit string. That is another design trade-off between implementation and user experience.

  38. Maria

    When using realloc, it is safer to store its return value in a temporary pointer first. If realloc fails, it returns null, and overwriting the original pointer immediately could lose the only address of the old block. Programs should check allocation results and exit gracefully when memory cannot be obtained.

  39. Hope

    The dynamically allocated array must also be freed when the program is done. For example, if the user enters three integers and each integer occupies four bytes, Valgrind can report a twelve-byte leak when the array is not freed. Adding free at the end removes that leak.

  40. Maria

    For a linked-list program, malloc allocates one node at a time. The program should check whether the returned node pointer is null before using it. Then it can assign the value, set the next pointer, and connect the node to the list.

  41. Hope

    The arrow operator makes those operations easier to read. If n is a pointer to a node, n->number means follow n to the node and access its number field. It is shorthand for (*n).number. Likewise, n->next accesses the pointer to the next node.

  42. Maria

    To append a node, a traversal pointer starts at the first node and continues while it is not null. If the current node’s next pointer is null, the program has reached the end and can set that next pointer to the new node. Otherwise, it advances with ptr = ptr->next.

  43. Hope

    Once arrays, pointers, and structs are available, they can be combined into more advanced structures. A hash table uses an array of buckets, where each bucket can contain a linked list. A hash function maps an input, such as a name, to a bucket number.

  44. Maria

    For a simple example, the first letter of a name can select one of 26 buckets. Names beginning with A go in one bucket, names beginning with B in another, and so on. The array gives constant-time access to the selected bucket, while the linked list handles however many names landed there.

  45. Hope

    A hash table can be much faster in practice than one long list, because each bucket is usually shorter. But the worst case is still linear if every name hashes to the same bucket. Good hash-function design aims to distribute values as evenly as possible.

  46. Maria

    The hash function does not have to use the first letter. It could use a last name, an identification number, a birth date, multiple letters, or another property. The design goal is to spread the data across buckets so that no individual linked list becomes unnecessarily long.

  47. Hope

    A binary search tree is another structure built from nodes and pointers. Each node has a value, a pointer to a left child, and a pointer to a right child. Values smaller than a node go to the left, and values larger than the node go to the right.

  48. Maria

    Searching begins at the root. At each node, you decide whether to stop, move left, or move right. In a balanced tree, each level represents another division of the remaining possibilities, so the height and search time are logarithmic in the number of elements.

  49. Hope

    The tree structure also avoids the fixed-size problem of an array because new nodes can be allocated as needed. However, the efficiency depends on the tree’s shape. The logarithmic behavior comes from a well-structured, balanced tree rather than from every possible arrangement.

  50. Maria

    The final structure is a trie, pronounced like “try.” It is a tree whose nodes contain arrays. To store a word, you follow one array entry for each successive character. A word such as Billy follows the path B, then I, then L, then L, then Y.

  51. Hope

    Words can share paths. Bob and Billy both begin with B, so their paths can reuse the same first node before branching at the next character. A trie can therefore find a word in a number of steps related to the word’s length, rather than to the total number of words stored.

  52. Maria

    That can provide constant-time behavior relative to a fixed maximum word length, but the cost is memory. Each node may contain a large array of possible character links, even when most of those links are unused. As with the other structures, the choice is a trade-off between speed and space.

  53. Hope

    A trie also needs a way to distinguish a complete word from a prefix. If both Bob and Bobby are stored, reaching the node for Bob must indicate that Bob is a word, while still allowing the path to continue for Bobby.

  54. Maria

    These structures are the foundation for a spell checker. A dictionary can be loaded into memory, and each word typed by a user can be checked against that data structure. The challenge is not only making the checker correct, but choosing a design that uses time and memory effectively.

  55. Hope

    So the big picture is that C gives you low-level control, but that control creates responsibilities. You must manage allocated memory, validate pointers, free what you allocate, and use tools such as debug50, help50, Valgrind, and rubber duck debugging to expose problems that a successful-looking run may hide.

  56. Maria

    And once you understand arrays, pointers, structs, and dynamic memory, you can build linked lists, hash tables, trees, and tries. Each structure solves a different problem by balancing access speed, insertion cost, memory use, and flexibility. Those foundations also make higher-level languages easier to appreciate, because their convenient features are built on ideas like these underneath.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent