1. Home
  2. Explore
  3. Computer Science
  4. Image Filters in C

Study methods

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

Image Filters in C

Speaker 1Speaker 2

Image Filters in C

16:33
0:00-16:33
  1. Michael

    Welcome back. Today we're exploring how C lets us organize data in memory, save information in files, and build increasingly powerful data structures. We'll begin with structs, which are especially useful in CS50's image-processing work, such as implementing the red filter in the forensic or "who done it" problem set.

  2. Hope

    A struct lets us create our own data type by combining existing types. For example, a student might have a name and a dorm, both represented as strings. We define it with typedef and struct, and we could add other fields too, such as an identification number, phone number, or email address.

  3. Michael

    It is common, though not required, to place that definition in a header file such as structs.h so multiple programs can use it. Once the custom type exists, we can declare an array of students. If the user enters an enrollment number, an array declaration can use that variable to request exactly that many student elements.

  4. Hope

    Then, inside a loop, we can ask for each student's name and dorm. The syntax students[i].name means: go to the i-th student in the array, enter that student's structure, and access the name field. The dot operator is needed because a struct contains several fields that we can access individually.

  5. Michael

    After collecting the information, we could print each student's name and dorm. But simply printing the data and then ending the program throws it away. To make it persist, we can open a file with fopen. The mode "r" is associated with reading, while "w" is associated with writing.

  6. Hope

    The result of fopen is stored in a FILE pointer. We must check whether that pointer is NULL, because opening a file can fail: the file may not exist, we may lack permission, or the computer may not have enough memory. NULL represents the absence of a valid address.

  7. Michael

    Instead of printf, we can use fprintf. It works similarly, but its first argument identifies the open file, so the formatted output goes into that file rather than onto the screen. Calling fclose afterward closes the file and completes the saving process.

  8. Hope

    One simple format is CSV, or comma-separated values. If we deliberately print commas between fields, a file such as students.csv can be opened as a basic spreadsheet, with each comma-separated value appearing in its own column. CSV files are useful for simple data, but searching increasingly large files becomes slower.

  9. Michael

    That limitation motivates databases, which are more powerful than treating a growing spreadsheet as a database. But underneath all of this, the computer is still storing zeros and ones in memory. We can think of memory as bytes with numbered locations, and those locations are addresses, also called pointers.

  10. Hope

    A running program's memory is divided conceptually into regions. The text segment contains the compiled zeros and ones of the program itself. Initialized and uninitialized data contain global variables, depending on whether they were given initial values, and environment variables can store values such as usernames or passwords outside the program's source code.

  11. Michael

    The two regions we'll focus on are the stack and the heap. When a function is called, it receives a frame on the stack containing its local variables and parameters. When that function returns, its frame is no longer trusted for future use, even though the physical memory still exists.

  12. Hope

    That explains the failed version of swap. The function might receive local variables named a, b, and temporary. It can successfully exchange the values of a and b inside its own stack frame, but the x and y variables in main remain unchanged because they occupy a different frame.

  13. Michael

    Pointers solve that by passing addresses instead of copies of values. In a declaration such as int *a, the a variable stores the address of an integer. But when the asterisk appears before a pointer expression, as in *a, it means follow that address and access the integer stored there.

  14. Hope

    So in pointer-based swap, we pass the addresses of x and y. The function can use *a and *b to reach the original variables in main, place one value in a temporary integer, and then write the values back into those original memory locations.

  15. Michael

    A useful analogy is a postal address. The pointer is like a map or address telling you where a building is, while *pointer means actually going to that building. Assigning y = x copies the address; it does not visit the address. If x contains address 100, then after that assignment both pointers contain 100 and refer to the same memory.

  16. Hope

    Uninitialized variables contain what are called garbage values. Those are not mysterious symbols; they are leftover bits from earlier uses of the same memory. C generally does not spend time clearing every newly used stack location, so unless the program initializes a variable, its contents cannot be trusted.

  17. Michael

    The heap serves a different purpose from the stack. It provides memory that can remain available beyond the lifetime of one function call. A function such as GetString cannot safely store a returned string in its own stack frame and then return that address, because the frame becomes invalid when the function finishes.

  18. Hope

    Instead, GetString can allocate the characters on the heap. malloc requests a chunk of heap memory and returns its address. That memory remains available until the program explicitly releases it with free. If allocated memory is never freed, the program develops a memory leak and can eventually slow down or run out of memory.

  19. Michael

    calloc is related to malloc, but it also clears or zeroes the allocated memory. realloc can resize an existing allocation. It may find a larger location, copy the old contents, free the old block, and return the address of the new block. The details are handled by realloc, although the operation can still take linear time because copying may be required.

  20. Hope

    A common pointer mistake is declaring int *x and int *y, allocating memory for x, and then immediately writing through y. Declaring y only reserves space for an address; it does not make y point to valid integer storage. Since y initially contains a garbage address, *y may attempt to access memory the program is not allowed to touch, causing a segmentation fault.

  21. Michael

    If we write y = x, both pointers refer to the same allocated integer, so writing through *y changes the same value that *x would access. But that does not allocate a second integer. To obtain separate storage, we would need another allocation.

  22. Hope

    The stack and heap can also collide conceptually. Too many nested or recursive function calls can exhaust the stack, producing a stack overflow. Repeatedly allocating memory can cause the heap to grow into the stack, producing a heap overflow. More generally, a buffer overflow occurs when a program writes beyond the boundaries of an allocated memory region.

  23. Michael

    A string is itself a buffer: an array of characters ending with a null terminator. Video buffering gives another example of a buffer. A player downloads bytes into an array so playback can continue even if the network briefly slows. If playback catches up with the downloaded data, the buffer becomes empty and the video pauses.

  24. Hope

    The dangerous version is writing more data than a buffer can hold. Suppose a function allocates an array of 12 characters but copies the entire length of an input into it without checking the length. An input of 13 characters writes one byte beyond the array, and a still longer input can overwrite neighboring variables and even the return address stored on the stack.

  25. Michael

    That can become a buffer overflow exploit. Since characters are represented as numbers and programs are represented as bits, an attacker may craft input that overwrites the return address with a new address. Instead of returning to the intended code, the function might be tricked into executing attacker-supplied instructions.

  26. Hope

    The basic defense is to check array boundaries and allocation sizes carefully. Tools help us find mistakes that are difficult to notice by inspection. Valgrind can detect memory-related errors and leaks, while help50 can make some of Valgrind's technical messages easier to interpret.

  27. Michael

    For example, if a program allocates space for ten integers, valid indexes run from zero through nine. Writing to index ten is an invalid write beyond the buffer. Valgrind may describe this as an invalid write of size four, because an int in that environment occupies four bytes.

  28. Hope

    After fixing the out-of-bounds write, Valgrind might still report that bytes are definitely lost. That indicates a memory leak: the program called malloc but did not call free on the returned pointer. Adding free with that same pointer allows the operating system to reclaim the block.

  29. Michael

    The hexadecimal values in Valgrind's output are generally memory addresses. Hexadecimal is simply another way to represent numbers, just as the hexadecimal signature bytes of a JPEG are another representation of the same underlying bits.

  30. Hope

    There is also a surprisingly practical debugging technique called rubber-duck debugging. Explain your code aloud, line by line, to a rubber duck, a wall, or even yourself. Hearing what you believe the program does can expose a mismatch between your explanation and the actual code.

  31. Michael

    Now let's use pointers to address a limitation of arrays. An array stores elements contiguously, back to back in memory. If an array of six elements is full and we need a seventh, we cannot safely place it outside the allocated region. We can allocate a larger array, copy all six elements, add the seventh, and free the old array.

  32. Hope

    That approach works, but it temporarily uses extra memory and requires linear time, O of n, to copy the elements. It can also fail when enough total memory exists but no single contiguous region is large enough. Memory fragmentation means free space may be separated into many smaller pieces.

  33. Michael

    A linked list avoids the requirement that elements be adjacent. Each node stores a value and a pointer called next to the next node. The nodes can be located anywhere in the heap, and the pointers stitch them together. A separate pointer, often called first, identifies the first node in the list.

  34. Hope

    Adding a node does not require copying the entire list. We allocate a new node, store its value, and adjust pointers. If order does not matter, inserting at the beginning takes constant time, O of one: update the new node's next pointer and update first. If the list must remain sorted, we may need to walk through it, making insertion O of n in the worst case.

  35. Michael

    Linked lists trade space and simplicity for flexibility. Every node needs extra space for a pointer, and the code is more complicated. We also lose random access: unlike an array, we cannot jump directly to element number three. To find a value, we follow next pointers from the first node.

  36. Hope

    In C, a node can be defined with an integer and a pointer to another node of the same type. The pointer is necessary because placing a complete node inside itself would create an infinite structure. When we have a pointer to a struct, the arrow operator follows the pointer and accesses a field, as in pointer->number.

  37. Michael

    To free a whole linked list, keep a temporary pointer. While the current pointer is not NULL, first save the address of the next node, free the current node, and then move to the saved next node. Saving next before freeing is essential because after freeing the current node, we must not depend on its fields.

  38. Hope

    A dynamic array offers another solution. Start with a pointer set to NULL and a capacity of zero. When the current size reaches capacity, call realloc to request room for one more integer, update the capacity, and then insert the value. This still may require linear copying, but realloc manages the resizing process for us.

  39. Michael

    The same design choices appear in abstract data structures. A stack supports push and pop and follows LIFO: last in, first out. A clean tray placed on top of a dining-hall stack is the tray a person is most likely to remove first.

  40. Hope

    A stack can be implemented with a fixed-size array, but that limits capacity. It can also use a dynamically resized array or a linked list. The abstract operations remain push and pop even when the low-level implementation changes. That separation is an API: users rely on documented operations without needing to know the implementation details.

  41. Michael

    A queue has the opposite ordering rule: FIFO, or first in, first out. It is appropriate for a line of customers waiting for phones because the person who arrived first should be served first. A queue can track its front so removing an element does not require shifting every remaining element forward.

  42. Hope

    Stacks and queues are not inherently good or bad; their usefulness depends on the application. A browser can use a stack while processing nested HTML elements, whereas a store line naturally behaves like a queue.

  43. Michael

    Trees provide another way to connect nodes. The top node is the root, nodes below it are descendants, and nodes with no children are leaves. In a binary tree, every node has at most two children, conventionally called left and right.

  44. Hope

    A binary search tree adds an ordering rule: values in the left subtree are smaller than the current node, and values in the right subtree are larger. To search for 22 in a tree whose root is 55, compare 22 with 55, move left, compare again, and continue. If the tree is reasonably balanced, each comparison eliminates roughly half the remaining possibilities, giving logarithmic search time.

  45. Michael

    The recursive search algorithm has four cases. If the tree pointer is NULL, the value is absent. If the target is smaller than the current node, search the left subtree; if larger, search the right subtree; otherwise the values are equal and we return true. A badly shaped tree can degenerate into something like a linked list, so logarithmic performance depends on balance.

  46. Hope

    Hashing tries to make lookup faster by mapping an input to a bucket. A hash function examines a value and produces a hash value, such as a number identifying one of several piles. Sorting cards by suit, or organizing exams by the first letter of a student's last name, are familiar examples.

  47. Michael

    A hash table can use linear probing when multiple values map to the same array position. If Alice and Bob occupy their expected positions but Brendan collides with Bob, we scan forward until finding an empty slot. This uses space efficiently, but clusters can form and lookup can eventually become linear.

  48. Hope

    Separate chaining handles collisions by making each table position point to a linked list. Every value is placed in its hash bucket, and multiple values can share that bucket by extending the chain. With a well-designed, reasonably uniform hash function, the chains stay short, making real-world lookup much faster than searching the entire data set.

  49. Michael

    Asymptotically, a hash table with chains may still be described in terms of the size of a chain, but dividing data into many balanced buckets can produce a major practical improvement. This is why a spell checker can be optimized not only for correctness, but also for the actual time and memory it uses.

  50. Hope

    A trie offers another lookup strategy. Each node contains an array of pointers, often one position for each letter. To store Maxwell, follow the pointer for M, then A, then X, then W, E, L, and L. A marker at the final node indicates that a complete word ends there.

  51. Michael

    Looking up a name in a trie depends on the number of characters in that name, not on how many total names are stored. Maxwell still requires the same sequence of seven letters whether the dictionary contains a thousand names or billions. For bounded-length human names, that is effectively constant-time lookup, although tries use substantially more memory.

  52. Hope

    So the larger lesson is that data structures involve trade-offs. Arrays provide simple storage and fast indexing but have fixed or resizing costs. Linked lists provide flexibility but use extra memory and lose random access. Trees, hash tables, and tries can accelerate searching, but each requires additional structure and careful implementation.

  53. Michael

    There are trade-offs in programmer time as well. A quick but poorly designed solution may save effort immediately while creating technical debt that must be repaired later. Good design balances correctness, execution time, memory usage, implementation complexity, and the long-term cost of maintaining the code.

  54. Hope

    And that brings together the major ideas: structs let us group related values, files let us preserve them, pointers let us refer to and connect memory, malloc and its relatives provide dynamic storage, and data structures such as lists, stacks, queues, trees, hash tables, and tries let us organize information for different kinds of operations.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent