CS50x - Lecture 4 - Memory
Overview
David J. Malan explains how C represents images, values, and strings in memory, building from hexadecimal addresses to pointers, dereferencing, pointer arithmetic, and dynamic allocation. He demonstrates why strings require deep copying and careful memory management, how pointers enable functions such as swap to modify caller data, and how C file I/O can persist and copy data byte by byte.
Key takeaways
- Hexadecimal is useful in systems programming because one hex digit represents four bits, so two digits compactly represent a byte and 0x clearly marks hexadecimal values.
- In C, a string is a char pointer to its first character, with the null terminator marking the end; assigning one string pointer to another aliases the same memory rather than copying characters.
- A genuine string copy requires allocating strlen(s) + 1 bytes, copying the null terminator as well as the visible characters, checking for NULL, and freeing memory allocated with malloc.
- C passes function arguments by value, so a function that must modify a caller's variable needs a pointer parameter and must dereference it, as in swap(&x, &y).
- Valgrind can reveal out-of-bounds writes and allocations that were never freed, including the invalid fourth index and 12-byte leak in the three-integer example.
- C file I/O uses file pointers and functions such as fopen, fprintf, fread, and fwrite; mode "w" overwrites a file, while mode "a" preserves existing content by appending.
Chapters
- Avery and Marie create a cat from green and purple Post-it notes, illustrating how a grid of pixels represents an image.
- Each screen pixel stores a color, and the total pixel count determines an image's finite resolution and storage needs.
- A one-bit image can encode black and white with 0 and 1; real images use more bits to represent RGB colors.
- Photoshop-style RGB codes use six hexadecimal digits, two each for red, green, and blue.
- The code 000000 represents black, while FFFFFF represents white.
- Each RGB channel ranges from 0 to 255, which fits in 8 bits.
- Hexadecimal is base 16 and uses the digits 0 through 9 followed by A through F.
- Its place values are powers of 16, so hexadecimal 10 equals decimal 16, not decimal 10.
- F represents decimal 15, making FF equal decimal 255.
- A hexadecimal digit maps directly to a group of four binary bits, such as F to 1111.
- Two hex digits therefore represent one byte, with FF encoding eight 1 bits and decimal 255.
- Programmers use the 0x prefix, as in 0x10, to make clear that a number is hexadecimal.
- Malan declares an integer n with value 50 and illustrates that an int commonly occupies four bytes.
- Computer memory locations can be represented as hexadecimal addresses, such as the illustrative 0x123.
- The %p format specifier prints a memory address, unlike %i, which prints an integer value.
- A pointer stores a memory address, and int *p declares a pointer to an integer.
- The expression &n obtains the address of n, so assigning p = &n stores that address in p.
- Using an int without the asterisk for p causes an incompatible pointer-to-integer conversion.
- On common 64-bit systems, pointers occupy eight bytes, allowing addresses for far more than 4 GB of memory.
- The pointer p contains n's address, while n contains the integer value 50.
- Diagrams often replace unwieldy hexadecimal addresses with arrows from pointers to their target values.
- The expression *p follows the address stored in p and accesses the integer at that location.
- With n set to 50 and p = &n, printing *p displays 50.
- The asterisk has different meanings by context: pointer declaration after a type, and dereferencing before a pointer expression.
- The string "Hi!" occupies four bytes: three character bytes plus the terminating null character, \0.
- Characters in a string occupy contiguous memory locations, so successive characters have successive addresses.
- The null terminator marks where the string ends, allowing code to traverse it from its first character.
- A C string variable stores the address of its first character, not the full character sequence inside the pointer itself.
- The CS50 library defines string as a typedef synonym for char *.
- Without the CS50 library, a program can use char * and pass it to printf with %s, which prints until \0.
- For a char pointer s, *s accesses the first character and *(s + 1) accesses the next character.
- Array notation such as s[0] is syntactic sugar for pointer arithmetic and dereferencing.
- Passing s, s + 1, or s + 2 to printf with %s prints successively shorter suffixes of the same null-terminated string.
- The == operator compares pointer addresses, so two separately entered instances of "hi" can compare unequal.
- strcmp(s, t) compares characters and returns 0 when the strings match.
- The string.h header provides strcmp, while %p can demonstrate that identical input strings occupy different addresses.
- Setting t = s copies the address, so both char pointers refer to the same characters in memory.
- Changing t[0] with toupper also changes what is observed through s.
- A true independent copy requires allocating a separate character buffer and copying the characters into it.
- malloc allocates a new memory block and returns its address; strlen(s) + 1 provides room for the null terminator.
- A manual copy loop must copy through index strlen(s), not stop before the terminating \0.
- The string.h function strcpy(t, s) copies the source into the destination, with the destination argument first.
- malloc can fail and return NULL, a special pointer value conventionally represented by address 0.
- Programs should check allocation results before using the returned pointer and avoid uppercasing a first character when strlen(s) is 0.
- Memory allocated with malloc should be released with free when no longer needed; failing to do so can cause a memory leak.
- The memory.c example allocates space for three integers with malloc(3 * sizeof(int)).
- Valgrind reports an invalid write when the program uses indices 1, 2, and 3 instead of 0, 1, and 2.
- Its leak report identifies the unfreed 12-byte allocation; adding free(x) and fixing the indices yields zero errors and no leaks.
- Declaring an array such as int scores[1024] does not assign meaningful values to its elements.
- Printing the elements before initialization exposes unpredictable remnants of previously used memory.
- Code should initialize values before reading them rather than treating existing memory contents as reliable.
- The Stanford claymation character Binky shows that declaring int *y does not make y point to a valid integer.
- Dereferencing an uninitialized pointer and writing 13 through it can corrupt memory or crash the program.
- Assigning y = x makes both pointers refer to the same allocated integer, so dereferencing either accesses that valid pointee.
- Olivia demonstrates swapping two drinks by using a third, empty glass as temporary storage.
- The corresponding C algorithm stores a in temp, assigns b to a, then assigns temp to b.
- A swap function taking two int arguments still fails to change its caller's variables because C passes arguments by value.
- Changing swap's parameters to int * lets the function receive the addresses of the caller's integers.
- Calling swap(&x, &y) and assigning through *a and *b changes the original values rather than local copies.
- The function uses temp = *a, then *a = *b, then *b = temp to complete the swap.
- The heap supplies dynamically allocated memory through malloc, while function calls and local variables use stack frames.
- The heap and stack have finite space; excessive allocation or unbounded recursion can make them collide or exhaust memory.
- A buffer overflow occurs when a program writes beyond a buffer's allocated bounds, potentially causing crashes or security problems.
- scanf with the %i format reads an integer from standard input, but it needs &n to write into the caller's variable.
- The program prints a prompt, calls scanf("%i", &n), then prints the resulting integer with printf.
- scanf and printf use familiar format specifiers, but scanf requires an address for values it must modify.
- A char * variable declared without an allocation contains an uninitialized address, so scanf("%s", s) writes to an unknown location.
- Even a fixed-size character array can overflow if the user enters more characters than the allocated capacity allows.
- CS50's get_string grows its allocation as needed, while safe raw C input requires careful buffer allocation and length limits.
- RAM is volatile, while files on a hard drive or SSD persist after power loss and program termination.
- C's stdio.h provides functions including fopen, fclose, fprintf, fscanf, fread, and fwrite.
- File operations use pointers to file structures, another reason pointers are necessary for low-level C programming.
- The phonebook program opens phonebook.csv with fopen and writes comma-separated name and number fields using fprintf.
- Opening with mode "w" truncates the existing file, so each new entry replaces earlier entries.
- Using mode "a" appends entries; fclose closes the file, and the resulting CSV can be opened in spreadsheet applications.
- The cp example opens a source file in read mode and a destination file in write mode using command-line arguments.
- A typedef names unsigned char as byte, and a loop uses fread and fwrite to copy one byte at a time.
- Closing both files completes the copy; binary mode can be used when data must be treated as raw bytes rather than text.
- The next problem set applies C memory and file techniques to BMP images, which store grids of pixels.
- Each pixel uses red, green, and blue values, enabling transformations such as grayscale, sepia, reflection, and blur.
- Iterating over image bytes also supports edge detection, which highlights boundaries such as the Charles River bridge against the sky.
Transcript excerpt
0:43 All right, this is CS 50, and this is week 4, the week in which we take off the proverbial training wheels that have been the CS 50 library and reveal to you all the more what's going on underneath the hood of a computer in terms of its memory. We'll also talk about files and how you can actually persist information for a long time whether. A file you've downloaded or today that you've created yourself, but first I just wanted to share some artwork that two of your classmates, Avery and Marie, kindly made before class, which is a picture made out of Post-it notes, uh, some green, some purple, which collectively from where you are looks like what? Yeah, so indeed it's a cat that they made using only zeros and ones or green and purple pieces. And in fact, even though this is fairly low resolution in that it only has a few pixels this way and a few pixels this way,
1:34 it's actually representative of how computers do actually store images underneath the hood. So let's actually start there. In fact, we've had this bowl of stress balls for some time here on the lectern, and if we take a beautiful photo of it, they look a little something like this. Of course, this too is a finite resolution. And by resolution I just mean how many dots go horizontally and how many dots go vertically, multiply those two together and you get some number of bytes, maybe in kilobytes, megabytes, or heck, if it's a massive image, it could be even bigger than that. But it is in fact finite. And if we zoom in on this image, you start to see a little more detail. But at the same time, if you keep zooming in,
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
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, CS50.