Image Filters in C
Transcript
[MUSIC PLAYING] DAVID MALAN: All right. This is CS50 and this is lecture five. And you'll recall perhaps that in this most current week, you've probably been tackling a little something like this. And if you don't actually have this experience from childhood, what we're referring to in this problem set is these kind of glasses that aren't 3-D glasses because it's both red eyes or sometimes it's just a big piece of plastic. But with this can you actually look up and see what the answer is supposed to be. And so this is the allusion to which we're referring and the goal ultimately in problem set five's who done it is to actually figure out how to implement that kind of red filter. But to do that, you first have to understand this thing, which at first glance, admittedly, looks pretty complicated. But if you dived into the problem already, you'll probably have wrapped your mind around at least
a few of these fields like the size of the image or the width of the image and the height of the image, which should be a little more reasonably straightforward. But to implement this, you've had to deal with something called a struct or a structure. And so in C, we have this feature, recall. And we didn't really play with this that much last time. But you've seen it now in forensics, or you soon will. And here we have the definition of a student. So when C was invented decades ago, they didn't foresee the need for a student data type. They had int and char and float and double. But we can invent our own data types much like in Scratch. We can make our own puzzle pieces as follows. Typedef to define a type, struct to say here comes a structure. And what is the structure known as student? Well in this case, I arbitrarily decided that a student would just have a name and a dorm and both of those would be strains.
And you can imagine putting other things in there like ID numbers, phone numbers, email addresses, or whatnot so that you can actually combine all of this information together. So let's just take a quick look at how you might use code like this. Here is a file called struct.h. It's common, but not necessary to declare your structures inside of a file that also starts with .h so that we can share it across multiple programs just like with other libraries' header files. And here I've taken those training wheels off as before where, string is actually just a white lie for char star. But this is really the same data structure and it's in a file called struct.h. So let's take a quick look now at a program that actually uses this in struct0.C. So let's take a look at what we've done here. In struct0.C we have some header files up top. But we also include this header file so that we have access to this new custom data type. And then in main we do a few things.
We first go ahead and ask the user for an integer called enrollment. So hopefully they'll give us a positive number. If we then do get back a number as expected in line 13, what do we do in English here? How would you just describe what line 13 is doing at this point in the term? Anyone yeah? AUDIENCE: [INAUDIBLE] DAVID MALAN: Yeah, give us an array of students of size enrollment. So even though on line 11 and prior we didn't know how many students we needed, we did get on line 12 that answer, the enrollment. And so on line 13 we declare an array using a variable saying, give me this many elements, this many students in my array to store things. And then we proceed, in the lines below, as follows. We start iterating over the enrollment from zero on up to enrollment. And we prompt the user on each iteration for a student's name and dorm. And the right hand side of those two lines of code is pretty familiar. You're just calling, get string.
But on the left hand side, we do have a slightly new piece of syntax. We have students bracket I, which gives you the i-th students in the array. But what piece of syntax perhaps jumps out at you? Especially if you've never programmed before? And we've not used this symbol just yet in this context. What looks different? Yeah. AUDIENCE: [INAUDIBLE] DAVID MALAN: Yeah, so the .name. So you can probably infer that .name and .dorm is somehow accessing the student's name and the student's dorm. And that's literally all that's happening. This dot operator tells the computer, go inside of the student's structure at that i-th location and store the string that's coming back from get string in that variable. And similarly, do the same for dorm. So it's like taking a struct and then looking inside of it and going very specifically to one of the elements therein. We've never needed this .operator before because in the past, any array,
any variable we've had has just been a string or an int or float. We haven't had anything to dive deeper into. So that's all that's going on there. We've encapsulated, so to speak, inside of a student structure, name and dorm. And then this last part is actually just a printing out of that same information. We're just printing out, so-and-so is in such-and-such a dorm by passing in those two strings using our familiar percent S. Now this program at the end of the day is kind of pointless because you prompt the user for some number of students' names and dorms, you print them out, and then you throw them away forever. And that's not all that useful of a program long term. And so we have in our second version of this program, struct 1.C a new trick, too. That's a teaser as well for the direction we're going in this problem set, next problem set, and beyond, where we're actually using files where files on a computer are just a whole bunch of bits, zeros and ones.
Those zeroes and ones follow some pattern. But we have yet to see a mechanism for actually saving files. But here's how we can do it. So above this line here, 21 and above, same program. Just get a bunch of students from the user, per their name and dorm. Then here line 24 we see something that's a little new, though you have seen this in the forensics problem so far. We call a function called F open, meaning file open. That takes two arguments, according to its documentation. The name of the file you want open and then the second argument is how you want to open the file. And even if you've never seen this before, what might the W there represent? AUDIENCE: [INAUDIBLE] DAVID MALAN: Yeah, right. So it's read and write are two of the most common operations for a computer. R would be read, W would be write. And this kind of makes sense if the goal now is to save these students to a file so that the program is actually useful if you run it again and again.
So here we have a new data type on the left. It's all caps, which is a bit of an anomaly, even in C. But file, star, file just says, hey, give me a variable of type file that can store the address of a file, so to speak. And technically, that's not the address of the file on disk. That's the address in RAM once you've opened the file. But for now, just assume that this is an abstraction for the file. And it's just called literally file. So what is line 25's purpose in life? Even though we've never written this code before now.
Yeah, what do you think? AUDIENCE: If the file exists. DAVID MALAN: If the file exists, or more generally, if the file was successfully opened. Because there could be bunches of things that go wrong. One, as you've implied, the file might not exist. Two, maybe you don't have permission so it exists but you can't open it. Three, maybe there's not enough memory in the computer to open yet one more file. So any number of things could go wrong. And recall, what is the special sentinel value that typically represents errors now that we're in the world of pointers? Null, so N-U-L-L in all caps is sort of the opposite of having a valid address. It means no such address. So we use it to check for errors. So that's all line 25 is doing. And then the rest of this is almost identical to the previous program, except we're not using print F. What are we apparently using? F print F and take a guess as to what the F in print F stands for?
Yeah, so file print F. So it works almost the same except it takes one more argument. The very first argument now is not a format string like it's been for ages now. It's instead a variable that references an open file and then the rest of this is all the same. So what's really cool about F print F is that you don't just print to the screen. You actually print to whatever file you've opened so that then, on the very last line here, when I call F close, that's equivalent to saving the file. And then the program just quits. And so what's neat about this in the end is if I go ahead and scroll up here, and let me go into my source five directory. Let me go ahead and make struct one. Structs.h not found. What did I do? Well, I just screwed up before class and misnamed this file so that didn't just happen. So now I've compiled the program. All right, so now let me go ahead and run this ./struct1 enrollment will be three.
And we'll say that it'll be Maria who is in Cabot House and Brian who is in Winthrop. And say David was, say, in Mather. Enter and nothing seems to happen. But if I type LS now and look inside this directory, notice that I have a file called students.csv deliberately named because if you've ever used Excel or Numbers, a very common file format is what's called the CSV, comma separated values format. And this is sort of like a very simplistic database.
If I open this you'll see that indeed, the contents of this file are separated by commas. And if I were to actually open this file up in Excel, each of these columns would open up visually in exactly that. So what I did with my printdef, if I go back to structs1.c, notice as I consciously included that comma there, to create this sort of faux database format. And just for good measure, let me see if I go to download from the IDE's file manager and I go ahead and open up students.csv.
And then if the program cooperates here, we have Microsoft Excel. And now I've made myself a tiny little spreadsheet. Now using c-code. Now we're going to find pretty quickly that this is not all that useful to make CSV files. Because the more and more rows we add to these files, the slower and slower it's going to get to search them. And so before long, as we transition next week and be onto web programming, we're actually going to replace spreadsheets or CSVs like this and actually replace them with something more powerful, namely databases. So that's a teaser then of what's to come. But where did we begin this conversation? It all kind of keeps coming back to what's inside of our computer, which we can continue abstracting away. You don't have to understand how this hardware works. But we previously had said that you can at least think about chopping up your computer's memory into a grid so that you can just number of the bytes.
So that you have specific locations otherwise known as addresses or pointers. Last time we clarified that not all memory is treated equal inside of the computer. Rather, different chunks of memory are used differently. So the top portion, so to speak, but there is no notion of top in reality. This is just an artist's rendition. So the top of your computer's memory might be the heap, whereby you store certain types of values and then down here is the so-called stack where you store other types of values. And if we zoom out there's actually different layers still of memory. So let's actually tease apart what's going on here. If, when you run a program, you have access to a gigabyte of RAM or two gigabytes, and indeed, that's what your Mac or PC does. No matter how much RAM you have, the computer typically gives you the illusion of having access to all of it. And so this might be two gigabytes, then, of memory. Well, one of the first things that happens
is that the zeros and ones that compose your program, whether it's called A.out or Caesar or Vigenere or Structs One, those zeros and ones are loaded way up top here in your computer's memory. So the text segment in memory is a weird name for the zeros and ones of your actual program. It's not ASCII text. It's like literally zeros and ones of your compiled program. Below that are what are generally called initialized data or uninitialized data. And this essentially just means any global variables you have in your program are stored here or here. If you gave them values at the top of your program, they're initialized by definition. And if you didn't, they're uninitialized. So the compiler just kind of lays those out a little bit differently. At the very bottom are something called environment variables, which we don't use too much but you use them in a few weeks for web programming.
You'll often store things like user names and passwords or other values that you don't want to save in your code. But you want the Mac or PC or server to have somehow access to. But these are the ones we'll talk about the most, stack and heap. And we saw a couple of examples of each of these, though, briefly. What did we use the stack for or claim it's used for last time? AUDIENCE: [INAUDIBLE] DAVID MALAN: Say again? AUDIENCE: [INAUDIBLE] DAVID MALAN: Int min void, and more generally, functions when they are called. Main is, of course, the go to one for all programs' beginnings. But it might call another function like swap. And swap itself might call something else, maybe printdef gets called. So every time you call a function, it gets a slice of or a frame of memory. And they go up and up and up as those functions get called. And this was ultimately illuminating, at least theoretically, as to why this program was broken.
The program we looked at last time, the swap and no swap programs, we claim that this implementation was wrong. And yet I think when Kate came up and we did the example with switching the Gatorade flavors, this is pretty much an interpretation of that into code. And it's correct in one sense and it's incorrect in another. In what sense was this code actually correct? In the no swap program. Because we did walk through it briefly with the debugger. AUDIENCE: [INAUDIBLE] DAVID MALAN: OK, we needed temporary container or variable in which to store one of the values or one of the Gatorade flavors. And by the time we got to this third and final line in this function, what could you say about A and B? AUDIENCE: [INAUDIBLE] DAVID MALAN: Yeah, they had in fact been swapped. And I saw that, I think, by plugging in, I think I struggled with the debugger so I used E print def at the last minute just to see what had happened after that very third line. So it works.
This function does swap A and B. But it did not swap what? AUDIENCE: [INAUDIBLE] DAVID MALAN: X and Y, which were the variables in main. And so recall the story we told last time, was that if we focus only on your computer stack, that sort of bottom portion of memory, when main is called, it gets a chunk of memory down here at the bottom because it's the very first function to be called. And it had variables, recall, called X and Y whose values were one and two. When main called swap, the other function we just saw, it had values called A, B, and also temp that initially were one and two. And eventually became two and one. But that picture kind of answers the whole question. The reason X and Y didn't change is because you literally change in that red version, just A and B. So we solved this problem, recall, last time with what new feature of C? AUDIENCE: [INAUDIBLE] DAVID MALAN: Pointers, so addresses.
Rather than just hand the function, the values you want to swap, give the function a road map, so to speak, to those values so that the function can go to the values you actually care about and move them wherever they are. And it's a strange looking syntax at first. It looks like multiplication all over the place. But it had two different uses. If you have the star or asterisk up here and a data type like int next to it, this is saying, hey computer. Give me a variable called A. But that's not going to store an int. It's going to store what? AUDIENCE: [INAUDIBLE] DAVID MALAN: Yeah, the memory address of an int and just as B is going to store the address of another integer. So those are kind of placeholders for the addresses. So down the road is the Science Center. So if the address of the Science Center is 1 Oxford Street, Cambridge, Mass 02138, that is it's postal address and it uniquely identifies that building.
Similarly inside of a computer do values have unique addresses. They're just much simpler. They're numbers, they don't have streets and zip codes and all of that. But it's the same exact idea. So here we still have a variable temp of type int. So give me a temporary variable just like Kate had the extra cup that was initially empty. *A, though, without a data type to the left of it, was like saying what? *A in this context is a sort of different English sentence than this one. This means give me a pointer to an int or declare for me a variable that will store the address of an int. But this says, go to that address. So it means A is in address, *A means go to that address so you can get at the value, which probably in the story, is one. *A means the same thing. Again, go to that address. And then, by the way, go to that address B.
Whatever that value is, put it where this finger is already pointing. And then *B means go to that address and put whatever was in the temporary cup of Gatorade, or in this case, the value one. So pointers, though kind of a very convoluted way of fixing this solve the problem fundamentally, because now rather than passing one and two, we instead passed in here the address of X and the address of Y that allowed the computer to then go to those locations in memory and actually
do what it is we wanted it to do. So long story short, this is how the computer stack is used. When you call a function, it gets a new slice of memory on top of whatever function called it. As soon as that function is done executing, this memory effectively goes away. It's technically still there, because it's hardware. It's not going to physically disappear. But now whatever next function main calls, maybe printdef, maybe something else, it will reuse this memory in any number of ways that it wants for its own local values and parameters. So given that definition, the fact that the stack, kind of like trays in the cafeteria grow up and down and up and down as a program calls functions and those functions return, where do garbage values actually come from?
AUDIENCE: [INAUDIBLE] DAVID MALAN: Old things that were in that memory. So I kind of made this sweeping claim in the past that you shouldn't trust variables if you yourself haven't put values in them, because they have so-called garbage values. But that actually has a very precise meaning. That means if you have called a function and it needs a variable that just happens to be here, and this is like a minute into your program's running, a whole bunch of different functions might have used and unused, used and unused that portion of memory. So they're just going to have zeros and ones lingering there in some pattern. The computer could be really defensive and it could just change these all to zeros bits all the time. And that could have been a reasonable design decision, but long story short, C does not do that. It would have just been time consuming, especially years ago when computers were slower. The language was younger.
And it just wasn't compelling to do that. So you just get garbage values, which I have typically just written as question marks. But that's why. There are garbage values there because they're your own previous values, or those of some functions. So the heap, meanwhile, was fundamentally different. So the heap is this upper portion of memory that is in some sense conceptually above the stack. And it's up here. And that's different in the sense that it's more for long term storage. The stack is for short term storage, just to use locally when a function is executing. But suppose your program is to run for a while, or suppose you want a function to allocate memory that does stick around and does not just immediately become garbage values. In fact, think about GetString. GetString is a function we wrote and its purpose in life is to get a string from the user, which is a whole bunch of characters. And consider this.
If GetString is called and therefore gets a slice of memory on the stack, and I type in Maria's name, M-A-R-I-A and then that gets a secret /0. Where is the M-A-R-I-A and /0 stored? Can it be, by this definition, stored on the stack? Why? AUDIENCE: [INAUDIBLE] DAVID MALAN: Exactly. So if we allocated space on the stack, which we could do with an array, and then return the address of that string, that would be valid in some sense, because you would have allocated the memory.
And I'll go ahead and draw it like this. If we had a function, GetString being called and GetString's being called by main, that might mean that GetString has this chunk of memory here. And if Maria or I go ahead and type in her name, that's like allocating space for M-A-R-I-A /0. And you can think of this as just being a whole bunch of bytes in that frame. So they do exist and they literally are stored in memory. And I could return the address of this first byte, whatever this is. Maybe this is byte 10 or 100 or whatnot. And I could return that address to main as GetString's return value. But as soon as I do that, yeah, exactly. The memory doesn't technically go anywhere. But it's no longer trustworthy. All of that is now garbage value. So you might get lucky. And if you try to print GetString's return value you might see Maria but maybe briefly, because the next time you call a line of code or somehow that memory's reused, Maria's name
might get overwritten with some other values because her name becomes, by definition, a garbage value. And you don't know when it's actually going to get reused. So that's not safe. So this is why the heap exists. If you need to keep your memory around for a while, like GetString is supposed to do, turns out you can allocate it just elsewhere that won't disappear until you yourself free it. And so that's when we introduced last time a couple of new functions, malloc for memory allocation and it turns out there's an opposite of it, free, which you'll need to use for future problem sets dealing with memory management in order to undo the allocation here. Otherwise you end up having what's called a memory leak. And the computer might slow down, run out of memory, because you're not giving it back. And as an aside, it turns out there's a couple of cousins of malloc, calloc and realloc. Calloc is kind of cool in that the C means clear.
So calloc is identical to malloc, but it zeros the entire chunk of memory for you. So if you just want to initialize to have no garbage values whatsoever, you can use calloc instead of doing it yourself with a four loop or something like that. Realloc, we're going to see, is a more powerful function that allows you to take a chunk of memory and somehow grow it. But we'll see what that actually means in a moment. But with this power comes great responsibility. And we saw that things can go horribly wrong for binkie when you misuse memory addresses. And recall that we looked briefly at this program by way of Nick's video from Stanford. And let's see what these lines of code actually represent here. So here and here I'm declaring two variables, X and Y, that are going to store what, generally speaking? Addresses of integers. So that's all that's happening there. This now, was a new line of code last time.
Where it's saying, call malloc, so allocate some amount of memory. How much memory do you want? Whatever the size of an int is. Odds are it's going to be four, maybe eight, some power of two or some multiple of two here, or a multiple of four. So here we get back what? A chunk of memory or specifically, its address and we store that in X. Meanwhile this line says, go to that address and put the special number 42 there. This next line blindly says, go to the address in Y and put the unlucky number 13 there. But that's where binkie had an accident because what was inside of Y at that moment in time?
AUDIENCE: [INAUDIBLE] DAVID MALAN: Memory it wasn't allowed to touch. And why? Be more precise. AUDIENCE: [INAUDIBLE] DAVID MALAN: So close. That's going explain the symptom ultimately but? AUDIENCE: [INAUDIBLE] DAVID MALAN: Exactly. I didn't ask for any memory whatsoever. So by default, even though this looks funky, int*y just means give me space for an address. So that means, give me four or eight bytes of memory in the computer's RAM.
But what is inside of a variable by default, have we claimed? Just garbage values. So there's going to be a number there, and numbers are our addresses. So it's going to look like there's an address there. So it is technically correct to say, go there. But it's like following a map where you have no idea where you're going. You might sort of walk off the edge of wherever you are. And that's when bad things happen. And so the visualization that Nick put together with claymation was this. If you have this and it turns out it doesn't matter if the star is on the left or on the right here. But we have conventionally put it over onto the right side, next to the variable. When you do int*X and int*Y, that's like saying, give me a chunk of memory or clay for each of these variables. And he just kind of circled the little arrowhead there on the string because there's memory for it. It's just not pointing anywhere specific. It's a garbage value at this moment in time.
The next chapter in this story was this. Allocate space for an int, drawn in white clay here. And Nick, because of the assignment, said X, which is again is a pointer, is now going to point to that chunk of memory. So it's no longer a garbage value. It points somewhere specific. That is why Nick was then able to say, go there. Follow the arrow, and put the number 42 there. But the next line of code, this one went horribly wrong because Y was not pointing anywhere. Nick tried to say, go there and put 13 but there is nowhere so the computer crashes. A segmentation fault, meaning that you touch the segment of memory that you should not have because you tried to go somewhere where it was just some garbage value. And the fix, recall, might be this, or a solution. If we instead kind of rewind and fix binkie. And say Y equals X, that's not allocating extra space. That's just saying, have Y point at the same chunk of memory as X.
Because again, X and Y are just addresses. So if the address is 100 in memory, now X is 100, Y is 100. They're both pointing at the same chunk of white clay. So if he then did *Y, gets 13, that says, go there. Update the number. And now 42 became 13. Very similar in spirit, in fact, to our capitalization example, when we pointed to strings last time, at the same chunk of memory. So any questions on the stack or as depicted here, by binkie, the heap? Malloc allocates memory from the heap.
But anytime you declare local variables or arrays inside of a function, that ends up on the stack. And thus far malloc is the only tool, or calloc or realloc, that gives us access to this new portion of memory depicted in white clay here and sort of depicted in our diagram up above. Any questions? Yeah. AUDIENCE: [INAUDIBLE] DAVID MALAN: Good question. So keep in mind that X and Y are both the same data types. They're both pointers to addresses.
So as such, if you're going to set one equal to the other, you have to just store the value that's in one inside of the other. Otherwise it would be trying to put an integer inside of a pointer, which isn't quite correct even though they're technically both numbers. So this is just saying, whatever address is in X, put that same address in Y it says nothing about going to that address. It's like making a photocopy of a map but not actually following that map yet. Until this line, which then says, go follow the copy of the map. And it turns out it leads you to the same location. Yeah? AUDIENCE: [INAUDIBLE] DAVID MALAN: So if you return, in C you can only return one value. So you're kind of in a bad spot because you ideally want to return two values, right? Both A and B you want to return B and A. There are ways you can work around that and kind of sort of return two values and see. But in short, it's much easier said than done.
Python will actually make that much easier. But the short of it in C is you can't return multiple values. And that ties our hands in this case. OK, so odds are, related to all of this, you've heard about this website, which is enormously useful when you're trying to learn some new language, when you're out in the real world trying to solve some problem because this is this wonderful community of people who post questions and answers and ideally link to canonical references so you can kind of understand why some answer is the way it is. But this actually has a very technical meaning, Stack Overflow. And stack, of course, is now a familiar concept. And you can imagine something like this picture eventually going very wrong if you call so many functions that you just kind of run out of memory. Or not even run out per se. What are you going to hit eventually if you keep calling function after function after function? The heap.
And then bad things are going to happen. If your stack frames and your local variables are so numerous that you start overwriting the heap memory, now values that you allocated with malloc might themselves get clobbered. So this is not the best design decision but it is the reality. And it's mitigated only by using a compiler that might help you notice this or by actually using more memory than you actually need. Now, Stack Overflow actually has a very technical meaning here, as does heap overflow. Stack Overflow means you overflow the stack. You just call so many darn functions that you just touch memory you shouldn't. Heap overflow would be the opposite. You keep calling malloc and malloc and malloc and the heap overflows the stack. Because for better or for worse, the stack is growing this way and the heap is growing this way. And eventually they're going to strike each other. So this is a more general way of saying buffer overflows.
A buffer it's just a chunk of memory that stores data or values. We people in the real world might have heard of this in the context of video, YouTube, or various video players. If you've ever seen the expression buffering, dot dot dot. It's the most infuriating thing. Something's about to happen in the movie or show you're watching. And the damn thing start buffering, buffering, buffering. What does that mean? Well, the video player, YouTube or something else, has a chunk of memory, which you can think of as an array. And loaded into that array are the zeros and ones that compose the movie or TV show you're watching. And those were downloaded over the internet. And what happens is, hopefully your internet speed is faster than the movie's own playback. So that even though you might be at the minute 10 in the video, hopefully your computer has downloaded minute 10 through 11 so that you have this built up buffer of bytes
that you have a whole minute where you can watch, even if your internet connection goes out. But when your video is buffering, it means you have this array of memory and you've kind of looked at or watched all of the bytes in it. And the buffer is now empty. But the opposite can happen, too. If you try downloading more bytes then you have memory for, you might try putting minutes of the video someplace they don't belong in your computer. Or if you call too many functions or if you call malloc too many times, you might overflow the chunk of memory that's been allocated. So buffers are all over the place. And indeed, a string as we know it is just a buffer. It's an array of memory and hopefully you will only put as many characters in that string as can fit in that chunk of memory. So what kinds of things can go wrong? This is a bit of a contrived example, but it comes with a couple of visuals just to paint
a picture of how adversaries can hack into systems that are written in languages like C. So here's a quick program. We're going to include string.h. And down here we have int main that takes command line arguments. Notice this function does not do any error checking at all. It's pretty stupid. It just calls a function foo and passes an argv[1]. So the idea here is that this is a program that if you take a command line argument, a word after the program's name, just gets blindly passed into the foo program. OK. So next, what does foo do? It accepts as input a string, a.k.a. char* and we're just calling it bar. And then it allocates an array on the stack called C of size 12. And then even if you've never seen this function before, you can maybe kind of infer from its name, mem copy, like memory copy. So it turns out this is going to copy into this memory whatever is in this memory up to this many bytes.
So if I type in Maria as the command line argument, M-A-R-I-A is five. So that means the length I typed in is going to be five. And this is going to copy five bytes from bar into C that's it. Now it's meant to be just a monster. This program is pretty useless at the end of the day. But it's kind of distilled a thread into the fewest lines of code. What does this actually look like or what's happening? We've called the function. We've allocated 12 bytes. We've copied those five bytes into those 12 bytes. So all is well in this story.
But what actually happens in memory? So here's a picture of the stack kind of zoomed in and nicely colorized. So stack is going this way. Heap is growing this way. And this is just showing you technically how things are laid out on the stack. I keep kind of simplifying the world by just drawing things as X and Y and A and B. But they actually follow a precise order. So specifically, if we have a local variable called bar, which we did for this function, it goes right there at the bottom. If you then declare an array called C, it goes right up there on top. And these are sized proportional. This is four bytes. This is going to be 12 bytes. So it all is kind of proportional size. And then it turns out, and we won't go into too much detail, but if you like this stuff, CS 61 and other classes will explore it, it turns out another thing that has always been tucked away on the stack secretly is what's called a return address.
So when main calls swap, it's like handing the keys to the car off to someone else. Like swap, go do your thing. But main kind of has to tell swap or any function it calls, how to get back to its chunk of memory so that execution can resume with main as soon as swap is done executing. And it's not its stack memory, per se. Recall that top portion of memory that I described as the text segment? All the zeros and ones that compose your program? It turns out that main, when it calls swap or some other function, it tucks its own return address, the address of the appropriate zeros and ones in that text segment, into four bytes here, or maybe eight bytes, the address to which swap should hand the keys back to you, so to speak. Otherwise it's like main handing the keys off to another function and then it never hears from it again so main's other lines of code never get executed.
So long story short, there needs to be an address or a map tucked away on the stack so that swap can hand control back to main. But what happens here when you actually use this memory? Well, it turns out that if we just number the bytes on the stack, and that was a size 12, the first one is zero, and the last one is 11. So zero through 11 gives us 12 total. So if we type in something like Maria or maybe more generally, hello, H-E-L-L-O, which is the same length, that's using six bytes technically, because the /0 and all is well. Fits comfortably in C and we've got room to breathe. But what if we don't type in Maria or hello? What if we type in a very long sentence that's more than 12 characters? Where are they going to end up? If you type in a longer string at the command line in argv[1], notice the code is flawed. You're going to check the length of the word that the user typed in,
copy all of its bytes from bar into C. But what if the length of the string you typed in is 13? What are you going to do? You're going to copy 13 bytes from bar into C, thereby filling all of these 12 bytes plus one more that you shouldn't be touching. And if the string is even longer than 13, if the adversary really typed a long sentence or phrase or word or whatnot, you're going to really exceed the boundaries of that buffer or that array. So what does this look Like Well, if you type in a much longer word, like A-A-A-A-A-A-A, you could end up overwriting these 12 bytes, also these four bytes, also these green bytes, whatever they are, and most importantly, even the red bytes that I described as the return address. Now A-A-A-A-A really isn't going to cause anyone any trouble because it's just a sequence of random ASCII characters. But characters at the end of the day are just numbers,
and numbers are just bits, and programs are just bits. So the threat here is that if you're a pretty sophisticated adversary, someone who really knows programming, you could technically write a program that does something really bad like delete all the files on a hard drive. Or send spam to everyone in your contacts. Or anything like that because at the end of the day the program that he or she has just written is just zeros and ones. If you then convert that program zeros and ones to the corresponding, even if weird-looking ASCII values, you could technically type a program at the command line in argv[1] just by typing out the funky characters on the keys that are not going to make sense to a human reading it. But those ASCII characters in the context of a program are going to be interpreted as code. And if you're really good, and frankly, it's not so much that you're really good. If by a lot of trial and error, you happen
to overwrite the return address in a program, you can trick the computer into not returning back to main, but to jumping to the very input you passed into the program. So A here implies attack, like attack code. So if you're really clever, you can pass in an appropriate pattern of zeros and ones, convert it to ASCII so the human can type them in at the prompt, overwrite this return address, and trick the computer program to return from this function not to main, but to like, this byte up here. And maybe this byte coupled with all of these others means delete all the files on this user's hard drive, send spam to everyone in their contacts. This is called a buffer overflow exploit, and it's incredibly shockingly common even these days. C is not commonly used for a lot of programs but it still is everywhere. And there's other languages, too, like C++ that lend itself to this. And even though this is still a little arcane
and you don't need to worry too much about the addresses on the screen, the fundamental threat here is that if you do not check the boundaries of your arrays and the amount of memory you've allocated and you touch memory you should not, very bad things can happen. You're effectively giving control to anyone on the internet who can use your program because he or she can be clever enough to inject their own zeros and ones into your program for execution. OK. So dear God, this is scary in a computer science sense. So what can we do to defend against this beyond just not writing bugs, which is never going to happen, right? Even the most advanced, best programmers still make bugs, especially as the software gets more and more complicated. We have eprintf and we have help50 and we have debug50 but there's other tools, too, like Valgrind which happens to be a tool for detecting memory leaks in a program and other memory-related issues.

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