11.2 - Encapsulation (2026-11-06)
Overview
Chris Bourke develops a C `Book` structure into a reusable interface with initialization, string formatting, dynamic creation, and cleanup functions. He then reviews Exam 3 topics including arrays, pointers, strings, memory management, and `strtok`, and previews upcoming coursework and Exam 4.
Key takeaways
- A C function cannot safely return a pointer to its local stack buffer; format into that buffer, make a heap-allocated copy, and have the caller free the returned string.
- A factory such as `create_book` can allocate a structure with `malloc(sizeof(Book))`, reuse an initializer, and return a ready-to-use `Book *`.
- A destructor for a structure must free every dynamically allocated field it owns, such as a book's title and author names, before freeing the structure itself.
- Use `.` for fields on a structure value and `->` for fields on a structure pointer; pass `&book_value` when a function expects a pointer.
- For a dynamically allocated matrix represented by a table of row pointers, free each row first and the table once afterward.
- C strings require one byte beyond their visible character count for `\0`, and dynamically allocated array lengths must be tracked separately by the program.
Chapters
- Music and vocals play from about 0:05 to 2:16.
- Chris Bourke begins the lecture recap at approximately 2:21.
- The previous lesson defined a `Book` structure with supporting `Person` and `Date` structures for author and reading information.
- Book utilities already included initialization, standard-output printing, and a deep string-copy helper.
- Use `.` to access a regular structure's fields and `->` to access fields through a structure pointer.
- A `book_to_string` function returns a human-readable book description so callers can send it to standard output, a file, or a socket.
- Pass the book by `const` pointer to avoid copying the entire structure and to signal that formatting will not modify it.
- The example formats the title, author, publication year, and average rating with `sprintf` into a character buffer.
- A local stack buffer cannot safely be returned; the example instead returns a dynamically allocated deep copy, then frees that returned string after printing.
- A `Book *` must point to allocated storage before `init_book` can write fields; an uninitialized pointer causes a segmentation fault.
- Allocate one structure with `malloc(sizeof(Book))`, using the type name rather than the pointer variable when calculating the allocation size.
- The `create_book` factory takes book data, allocates the structure, calls `init_book`, and returns the resulting pointer.
- The existing initializer supports reuse: it fills an already allocated book, while the factory handles allocation as well.
- Each book owns three dynamically copied strings in this example: its title, the author's first name, and the author's last name.
- Free those three fields before freeing any dynamically allocated `Book` itself; freeing only the structure leaves its strings leaked.
- A `free_book` destructor centralizes field cleanup and accepts a `Book *`; pass `&b1` for a regular structure and `b3` for a pointer.
- The final cleanup run reports zero errors and no memory leaks in Valgrind; do not pass stack-allocated structures themselves to `free`.
- Questions 1 and 2 review static versus dynamic allocation and allocating 20 integers with the correct `malloc` size calculation.
- For a seven-element array, the final valid index is 6, not 7; using a negative index produces undefined behavior.
- Freeing memory that was not dynamically allocated is invalid, while failing to free allocated memory causes a memory leak.
- The buggy array-reversal function swaps elements past the midpoint, reversing the array and then reversing it back.
- A dynamically allocated two-dimensional array is built row by row, with an `int *` for each row and correct row and column counts.
- Array length is not automatically available for dynamically allocated arrays, so the program must retain the element count in an integer variable.
- A shallow copy makes two pointers refer to the same memory; changing an element through one pointer changes what the other sees.
- C strings need a null terminator, so storing a string of length 9 requires 10 bytes; copying `John` into only 4 bytes risks undefined behavior.
- `strtok` starts tokenizing CSV data with the input string and comma delimiter; later calls continue with a null first argument.
- Questions 20 and 21 revisit memory leaks and freeing a dynamically allocated matrix: free each of its `n` rows, then free the table of row pointers once.
- A pointer into `Hello World!!!` at the `W` prints the remaining substring, `World!!!`; overwriting a buffer with `world` before appending exclamation marks produces `world!!!`.
- `sprintf` writes formatted text to a character buffer, while `printf` writes to standard output; the buffer is the first `sprintf` argument.
- The C standard string declarations are provided by `string.h`, and Bourke notes that operating systems generally reclaim a process's memory when it exits.
- The next class will integrate the new `Book` structures and helper functions into the original book demonstration program.
- The following module introduces recursion, and the next regular exam is planned to cover file I/O and structures, with possibly a small amount of recursion.
- Bourke says the lowest regular exam score will be dropped after Exam 4; the comprehensive final exam will not be dropped.
- The schedule includes no Friday class because Bourke will travel to a conference, followed by a Thanksgiving break with no lecture or lab.
Transcript excerpt
0:05 [music] [music] [music] [music] [music] >> I want to love somebody. [music] I hear you need somebody to love. [music] Oh, I want to love somebody. I hear you looking for someone to love. 'Cause you need to
0:54 be back in the arms [music] of a good friend. And I need to be back in the arms [music] of a girlfriend. [music] I didn't know nobody. [music] And then I saw you coming my way. And I didn't know nobody. [music] And then I saw you coming my way. Don't you need to be [music] back in the arms of a good friend. Oh, just honey, believe me. I sure love to [music] call you my girlfriend.
1:43 [music] Woo! [music] All right. >> [music] [music] [music] >> All right. So, we started using structures last time. We went through a process of defining structures for a book, and then we also defined
2:30 them for ancillary structures for a person, which it represented the author, and then the date, which was used for date of birth for the author as an example, and then the date that the book was read. We also went through a process whereby we created a couple of utility functions. Those utility functions that we were making were to be able to print a book, right, to the standard output, to initialize a book, right? And then some supporting utility function here to do a deep string copy for us. We then use those so that everything looks nice and crisp and clean over here, where we are using using these functions to do all the heavy lifting for us, all right? Once once you've defined a structure, you can use them by declaring them like a regular old variable. So, instead of
3:19 int x equal to 42, you would have book
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Chris Bourke.