Memory
Harvard CS50 Introduction to Computer Science, lecture 4, explained in plain English
Want this lecture to stick? In LessonBound you get checked practice questions for every part, can ask about anything you don't get, and can listen with your screen off. Free, no ads.
Learn this lecture freeWatch or read the original lecture: the course website.
Part 1 · 0:00–10:00
Pictures on a computer are grids of tiny dots, and each dot is stored as a pattern of zeros and ones.
Key ideas
- Week 4 looks at what is happening inside the computer, so you know the building blocks behind the code you write. It also covers common files like images, GIFs, and PNGs. 1:01
- A picture is a grid of tiny dots called pixels. Resolution means how many of these dots fit on a screen, and more, smaller dots make a clearer image. 4:10
- A simple picture can be stored as zeros and ones, where each zero or one stands for one dot. In the lecture's example, zero means black and one means white. 5:15
- A color is written as an amount of red, green, and blue mixed together, with a hash sign and three pairs of characters. Solid black is 000000, and solid white is FFFFFF. 8:09
- Computers often write these color values in hexadecimal, a number system that uses the digits 0 to 9 and then the letters A to F. So FF stands for 255, the highest amount of one color. 9:15
Words to know
- pixel
- One tiny dot on a screen. A picture is a grid of these dots.
- resolution
- How many dots or pixels fit on a screen. More dots usually means a clearer picture.
- RGB
- Short for red, green, blue. It is a way of making any color by mixing amounts of these three colors.
- hexadecimal
- A way of writing numbers using 16 symbols: the digits 0 to 9 and the letters A to F. It is a shorter way to write long binary patterns.
Example
Think of a mosaic made of small square tiles, where each tile is one solid color. From far away you see a clear picture, but if you zoom in close, you only see the tiles. Images on a computer work the same way, with pixels as the tiles.
3 checked practice questions for this part are in the app.
Part 2 · 10:00–20:00
This part explains hexadecimal (base 16) numbers and shows how computers use numbered addresses to find bytes in memory.
Key ideas
- Hexadecimal, or base 16, uses the digits 0 to 9 and then the letters A to F, giving 16 symbols in all. A is 10, B is 11, and so on up to F, which is 15. 10:00
- One hexadecimal digit can stand for four bits, so two hexadecimal digits can stand for one full byte of eight bits. This is why programmers use hex so often. 12:54
- Computer memory can be pictured as a grid of bytes, and each byte has a number, called its address, that tells you where it is. 15:06
- Because hex digits look like ordinary numbers, a 0x in front of a number tells the reader that it is written in hexadecimal. The 0x does no math. 16:09
- A variable is stored at some address in memory. In C, the ampersand (&) asks for that address, and the asterisk (*) follows an address to see what is stored there. 19:02
Words to know
- hexadecimal
- A way of counting in base 16, using the digits 0 to 9 and the letters A to F.
- byte
- A unit of computer memory that holds eight bits, or eight zeros and ones.
- address
- The number that tells you where a piece of information sits in memory, like a house number on a street.
- dereference operator
- The asterisk (*) in C. It takes an address and lets you see or use the value stored at that address.
Example
Think of a long street of mailboxes, each with a number painted on it. The number tells you where the box is, and the box holds one letter, just as an address in memory tells you where a byte is and the byte holds a value. If you know the number, you can walk straight to that box.
3 checked practice questions for this part are in the app.
Part 3 · 20:00–30:00
This part explains how C uses addresses: the ampersand finds where a variable lives, a pointer stores that address, and star reaches the value stored there.
Key ideas
- The ampersand (&) in front of a variable gives you its address, which is where the variable lives in memory. The %p format code tells printf to show an address. 20:00
- A pointer is a variable that stores an address. You declare one with int star p, which means p will hold the address of an integer. 21:43
- Star p means go to the address that p holds and look at the value there. So if p holds the address of n, star p gives you the 50 stored in n. 23:53
- The star symbol has two jobs here, and neither one is multiplication. In a declaration it marks a pointer, and before a pointer name it means go to that address. 24:37
- Pointers usually take up eight bytes, which is enough room to count to many more addresses. A pointer's stored value is the address of another value. 27:09
Words to know
- address
- The location of a value in the computer's memory, like a house number for data.
- ampersand
- The & symbol. Put in front of a variable, it gives you that variable's address.
- pointer
- A variable whose job is to store an address, so it points to where another value lives.
- dereference
- Using star on a pointer to go to the address it holds and get the value stored there.
Example
Think of a pointer as a treasure map. The map does not hold the treasure itself, but it tells you exactly where to go to find it. Using star p is like following the map to the spot and opening the box to see what is inside.
3 checked practice questions for this part are in the app.
Part 4 · 30:00–40:00
A string is really a pointer, which is an address that shows where the string's characters start in computer memory.
Key ideas
- Memory works like a row of mailboxes, and each mailbox has an address. A pointer is a value that holds one of these addresses, like an arrow to a location. 30:20
- The string "HI" takes four bytes, not three, because a hidden null character is stored at the end. The double quotes add this character for you. 31:25
- The variable s does not hold the letters themselves. It holds the address of the first character, so s is a pointer. 33:11
- The null character marks where the string ends. So one address is enough to find the whole string: start at the address and read until you hit the null character. 34:15
- The ampersand (&) asks for the address of a character, and %p is the format used to print an address. 38:15
Words to know
- pointer
- A variable that stores an address in memory, pointing to where some data is kept.
- null character
- A hidden character with all zero bits that marks the end of a string.
- byte
- A unit of memory that holds eight bits. In this lesson, each character in a string takes one byte.
- ampersand
- The & symbol. Placed before a variable, it means 'give me the address of this.'
Example
Think of a street where the houses are numbered in a row. If you know the address of the first house, you can walk to the next ones by counting along the street. A string works the same way: the pointer gives the first address, and the null character tells you when to stop.
3 checked practice questions for this part are in the app.
Part 5 · 40:00–50:00
This part shows that the string type you have been using is really a char star, which is a memory address, and it explains how C uses addresses to work with text.
Key ideas
- The string type used since week one is a CS50 shortcut that hides a lower-level idea. In plain C, a string is a char star. 40:00
- A char star is an address: the memory location of the first character in a string. The star means the variable holds an address, not a single character. 42:05
- When you put double quotes around text, C automatically stores the address of the first character, so you do not need an ampersand. 43:52
- typedef lets you give an existing data type your own name. The CS50 header uses this to make the word string mean char star. 44:36
- Pointer arithmetic means doing math on addresses. Adding one to an address moves you to the next byte in memory. 47:48
Words to know
- char star
- A variable that holds the memory address of a char, which is often the first character of a string.
- address
- The number that tells you where a piece of data is stored in computer memory, like a house number on a street.
- typedef
- A keyword that gives a type a new name of your own, such as calling an int an integer.
- pointer arithmetic
- Doing math with addresses, such as adding one to move from one byte to the next byte.
Example
Think of a long street where every house has a number. If you know the number of the first house, you can find the next house by adding one, and so on. A char star works like that first house number, and pointer arithmetic is the adding.
3 checked practice questions for this part are in the app.
Part 6 · 50:00–1:00:00
This part shows that pointers are addresses underneath, and that comparing two strings with == checks their addresses, so strcompare is needed to compare their letters.
Key ideas
- Adding a number to an address moves you to a later spot in memory. So s + 1 points to the second character of a string, and s + 2 to the third. The lesson calls this pointer arithmetic. 50:20
- Array syntax like s[1] is a shortcut. The compiler turns it into *(s + 1), which means go to that address and read the value there. The lesson calls this syntactic sugar. 51:22
- A string is really the address of its first character. When you use == on two strings, you compare those two addresses, not the letters. Two copies of "hi" stored in different places count as different. 57:10
- strcompare compares the letters one by one, from left to right. It returns zero when the strings match. For different strings, the sign tells you which one comes first, but the exact number has no set meaning. 58:40
Words to know
- pointer arithmetic
- doing math on an address, such as adding 1 to move to the next byte in memory.
- dereference operator
- the star symbol (*), which means go to the address and look at the value stored there.
- syntactic sugar
- an easier way to write something that the compiler quietly turns into a longer form.
- strcompare
- a built-in function that compares two strings letter by letter and returns zero if they match.
Example
Think of two houses on the same street with the same name written on their mailboxes. If you ask whether the two houses are the same house by checking their addresses, the answer is no, even though the names match. strcompare is like walking up to each mailbox and reading the name yourself to see whether they match.
3 checked practice questions for this part are in the app.
Part 7 · 1:00:00–1:10:00
This part shows why comparing and copying strings with the normal operators goes wrong, and how malloc and a careful copy loop fix it.
Key ideas
- Two strings that look the same can live at different addresses in memory. So comparing them with == checks the addresses, and it will say they are different even when the words match. 1:01:28
- The %p format prints the raw address stored in a string. The %s format makes printf follow that address and print the text stored there. 1:01:05
- Writing t = s copies the address, not the letters. Both names then point to the same text, so changing one changes the other. 1:04:05
- To make a real copy, malloc asks the operating system for a fresh block of bytes. The block must be big enough for every letter plus one extra byte for the null character. 1:06:55
- The copy loop must also copy the null character at the end. Without it, the copy does not know where the string stops. 1:09:04
Words to know
- address
- The location in computer memory where a value is stored, written as a hexadecimal number.
- malloc
- A function that asks the operating system to set aside a number of bytes that your program can use.
- null character
- A special hidden character, written backslash zero, that marks the end of a string.
- char star
- The type written as char *, which means the variable holds an address of a character, such as the start of a string.
Example
Imagine two houses built from the same blueprint. They have the same layout, but they are two different houses with two different street addresses. If you compare their street addresses, they will not match, even though the blueprints do.
3 checked practice questions for this part are in the app.
Part 8 · 1:10:00–1:20:00
This part explains how a C program asks for its own memory with malloc, how to check that the request worked, and how to give that memory back with free.
Key ideas
- malloc gives your program a chunk of memory and returns the address of its first byte. You must remember how far the chunk goes, and you must put the null character at the end of a string yourself. 1:10:21
- The operating system tracks how big each chunk is, so it won't hand the same bytes to someone else. But C does not check your array bounds for you. 1:11:27
- malloc can return null, which means there was not enough memory. Your program should check for this and stop early if it happens. 1:12:12
- Every block of memory you get from malloc should be given back with free when you are done. If programs keep asking for memory and never free it, the computer can slow down or crash. 1:14:18
Words to know
- malloc
- A built-in function that asks the computer for a chunk of memory of a size you choose, and returns the address of its first byte.
- free
- A function that gives a chunk of memory back to the computer so it can be reused. It is the opposite of malloc.
- null
- A special value that is the address zero. C uses it as a signal that something went wrong, such as there being no memory left.
- valgrind
- A tool that checks how your program uses memory and shows you the mistakes it finds.
Example
Think of malloc like renting a row of lockers at a gym. The gym tells you the number of the first locker, and it keeps track of how many lockers you rented. You are responsible for not going past the end of your row, and when you are finished, you give the lockers back so someone else can use them.
3 checked practice questions for this part are in the app.
Part 9 · 1:20:00–1:30:00
This part shows three common memory mistakes in C (forgetting to free memory, using variables that were never set, and using pointers that point nowhere) and how a tool called valgrind helps find some of them.
Key ideas
- Valgrind is a tool that checks a program for memory-related bugs. It does not catch logic mistakes or syntax errors. It reported an invalid write at line nine, which pointed to writing past the end of the array. 1:20:00
- Every time you call malloc to get memory, you should call free when you are done with it. If you forget, the memory is lost, which is called a memory leak. 1:20:00
- If you declare a variable and never give it a value, it holds a garbage value, which is leftover junk from earlier use of the computer's memory. Never trust a variable unless you have set it yourself. 1:20:00
- A pointer that never got memory of its own points to an unknown place. Using star on it (dereferencing) means touching memory you should not touch, and that can crash the program. 1:20:00
Words to know
- valgrind
- A helper tool you run before your program name. It watches your program and reports memory mistakes, like a teaching assistant checking your work.
- memory leak
- Memory your program asked for and then never gave back. It is like borrowing tools, never returning them, and then losing track of where they are.
- garbage value
- A random number left over in memory from earlier use. It is there when you have not put a number in a variable yourself.
- dereference
- Following a pointer to the place it points to and using what is there. In C you write a star before the pointer name to do this.
Example
Think of a used notebook someone gave you. Some pages have old scribbles on them, and you cannot tell what is important. You would not copy anything from those pages until you wrote your own notes first, which is how you should treat a variable you have not set.
3 checked practice questions for this part are in the app.
Part 10 · 1:30:00–1:40:00
This part explains how pointers work (following them to their values and pointing them at the same place), and why a swap function failed because it only received copies of the variables.
Key ideas
- Dereferencing a pointer means following its arrow to the place it points to, called its pointee, so you can read or change the value there. 1:30:00
- A pointer must be set to point somewhere before you dereference it. Allocating the pointer alone does not give it a pointee, so dereferencing it fails. 1:30:41
- Pointer assignment changes where one pointer points, so it points to the same place as another pointer. It does not change the values stored in the pointees. 1:31:03
- In C, passing by value means a function receives copies of the values it is given. So the swap function swapped its own copies and left x and y in main unchanged. 1:36:08
- Each function call gets its own stack frame, a block of memory on the stack. When the function returns, the computer forgets that memory, and the function's copies go away with it. 1:38:57
Words to know
- pointee
- The value or place that a pointer points to. Think of it as the thing the pointer's arrow leads to.
- dereferencing
- Following a pointer to its pointee so you can use or change the value stored there.
- pass by value
- Giving a function a copy of a variable's value, so changes inside the function do not affect the original variable.
- stack frame
- The block of memory the computer sets aside on the stack for one function call, holding that function's variables and copies of its arguments.
Example
Imagine two glasses, one blue and one orange, that need to trade their liquids. Pouring straight across fails, so you need a third empty glass called temp to hold one liquid while the other moves. The swap function had no such working plan for x and y, so it only moved copies of the values.
3 checked practice questions for this part are in the app.
Part 11 · 1:40:00–1:50:00
This part explains why a swap function that copies values fails, and how pointers (addresses) let a function change the original variables, with a short warning about memory overflows.
Key ideas
- Passing by value means the function gets a copy of each value. Changes made to the copies never reach the original variables, so the first swap function only swapped its own copies of a and b. 1:40:00
- To fix this, you pass the address of each variable, which is where it sits in memory. This is called passing by reference or passing by pointer. 1:40:40
- The star symbol (*) means 'go to this address and use the value stored there.' The swap function can then reach the original x and y and change them directly, even though it returns nothing. 1:41:41
- The ampersand symbol (&) does the opposite of the star. It gives you the address of a variable, so main must pass &x and &y when it calls the new swap function. 1:45:46
- Memory can run out. If a program uses too many stack frames or too much heap memory, it can overflow. A buffer overflow happens when a program writes more into a chunk of memory than it has room for, and this is why getting user input safely in C is hard. 1:47:59
Words to know
- pass by value
- Giving a function a copy of a value. The function can change its copy, but the original stays the same.
- pointer
- A variable that holds the address of another variable, so it can lead you to where that value is stored in memory.
- address
- The location of a piece of data in the computer's memory, like a house number for a value.
- buffer overflow
- What happens when a program uses more space in a chunk of memory than that chunk can hold, which can spill into other memory.
Example
Think of a treasure map. If you give someone a copy of the treasure's value, they can change their copy, but the real treasure stays put. If you give them the map with the exact spot marked, they can go to that spot and change the real treasure. Passing a pointer works like giving the map.
3 checked practice questions for this part are in the app.
Part 12 · 1:50:00–2:00:00
This part shows how to get an integer and a string from the user in C without the CS50 library, and why a wrong memory address causes a segmentation fault.
Key ideas
- To get an integer with scanf, you pass a format code like %i and the address of the variable (using &n). Passing the address lets scanf change the value of n, which passing n alone would not do. 1:51:27
- A string in C is stored as a char star, which is the address of its first byte. So you pass s to scanf without an ampersand, because s already holds an address. 1:53:56
- A char star that has not been set to a valid location holds a garbage value. When scanf writes to that bad address, the program touches memory it does not own and crashes with a segmentation fault. 1:56:34
- Declaring s as an array of four characters gives enough room for "hi!" plus the null character. Typing a much longer string writes past those four bytes, which also causes a segmentation fault. 1:59:23
Words to know
- scanf
- A function that reads input from the user's keyboard and stores it in a variable. You tell it what kind of input to expect with a format code.
- segmentation fault
- An error that happens when a program touches a part of computer memory that it was not allowed to use.
- garbage value
- Whatever random pattern of bits happens to be in memory before the program sets a variable to something known.
- pointer
- A variable that holds the address of a place in memory, rather than a normal value like a number.
Example
Imagine a parking lot that rents you four spaces, and you park five cars. The fifth car ends up in a space you never rented, and the lot manager shuts things down. In the same way, a program that asks for four bytes but writes five ends up touching memory that belongs to someone else.
3 checked practice questions for this part are in the app.
Part 13 · 2:00:00–2:10:00
This part explains why C makes reading text from users hard, and shows how to save data to a file that persists after a program ends, using a phonebook example.
Key ideas
- You cannot know in advance how long a string a user will type is. The CS50 getstring function gets one character at a time and keeps asking the computer for more memory as needed, so you do not have to guess a size. 2:00:43
- The lesson says scanf is dangerous to use with strings, and that it lacks some of the error handling the CS50 library provides. That is why the course uses getstring for text. 2:01:03
- File functions let a program open, write, and read files on the hard drive. The fopen function opens a file and returns a pointer to it, and fclose closes it. 2:02:33
- The phonebook program uses fopen in append mode, which adds new contacts to the end of a CSV file, then fprintf writes the name and number to that file, and fclose closes it. Each run adds more lines to the file. 2:05:07
- Any time a function returns a pointer, you should check whether it is NULL. NULL usually means something went wrong, so the program should stop instead of trusting the value. 2:08:43
Words to know
- fopen
- A C function that opens a file so a program can use it. It returns a pointer that points to the open file.
- CSV
- Short for comma-separated values. It is a plain text file where commas separate the values in each row, so spreadsheet programs can open it as columns.
- NULL
- A special value that means a pointer points to nothing. When a function returns NULL, it usually means something went wrong.
- segmentation fault
- A memory error that happens when a program tries to use memory that does not belong to it, which makes the program crash.
Example
Think of writing a grocery list on a notepad where you keep adding pages as you need them, instead of guessing how many pages you will need at the start. The getstring function works this way, adding memory one character at a time as the user types.
3 checked practice questions for this part are in the app.
Part 14 · 2:10:00–2:16:51
This part shows how to write a simple C program that copies a file one byte at a time, using command line arguments, fread, and fwrite.
Key ideas
- The main function can take argc and argv, which hold the words typed on the command line. Here, argv[1] is the file to copy and argv[2] is the name of the copy. 2:10:20
- The program opens the original file in read binary mode and the new file in write binary mode. Binary mode is used because images are zeros and ones, not text. 2:10:41
- The function fread reads one byte at a time into the variable b. It needs the address of b so it knows where to put the byte, and it returns how many bytes it read. 2:12:34
- A loop keeps copying while fread succeeds. When fread reaches the end of the file, it returns zero and the loop stops. Then fwrite writes each byte to the new file, and both files are closed. 2:13:17
- A bitmap file stores an image as a grid of pixels, each with x and y coordinates. Because of this, code can read and change the pixels to make filters like black and white or blur. 2:15:06
Words to know
- argv
- A list of the words typed after a program's name on the command line. argv[1] is the first word after the program name.
- binary mode
- A way of opening a file that treats its contents as raw zeros and ones, instead of text. It is used for files like images.
- fread
- A function that reads one or more bytes from a file into memory and reports how many bytes it read.
- bitmap
- A type of image file, with a .bmp ending, that stores a picture as a grid of pixels.
Example
Copying a file this way is like copying a book by reading one letter at a time and writing each letter onto a new page in the same order. You keep going until you reach the last letter, and then you stop. The new book ends up identical to the original.
3 checked practice questions for this part are in the app.
← Week 3: Algorithms · Week 5: Data Structures →
Notes written by AI (Claude) from the lecture's official transcript, so check anything important against the lecture. Harvard CS50 · CC BY-NC-SA 4.0 · not affiliated with or endorsed by Harvard. These notes are shared under the same license.
LessonBound · Free lecture notes · Privacy · Terms · New York