1 / 78

Computer Memory, Addresses, and Pointer Variables in C

This presentation is intended to be viewed in slideshow mode. If you are reading this text, you are not in slide show mode. Hit the F5 function key to enter slideshow mode. Computer Memory, Addresses, and Pointer Variables in C. Roadmap. Background: Computer memory and addresses

hallie
Download Presentation

Computer Memory, Addresses, and Pointer Variables in C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. This presentation is intended to be viewed in slideshow mode. If you are reading this text, you are not in slide show mode. Hit the F5 function key to enter slideshow mode. Computer Memory, Addresses, and Pointer Variables in C

  2. Roadmap • Background: Computer memory and addresses • The mechanics of pointers: Syntax and semantics • Examples of some of the major uses of pointers: • Functions with deliberate side-effects • Dynamically linked data structures

  3. Units of Memory • Computer memories consist of many identical units (bunches of bits), each with its own unique address  width or size units of memory ••• 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB addresses (usually shown in hexadecimal) • The address is how the hardware picks one bunch of bits for the CPU to work with and not some other bunch; it is nicely analogous to the street address for a house • The byte addressable memories used in personal computers store 1 byte (8 bits) at each address • Word addressable memories are used in higher performance machines and store multiple bytes at each address

  4. Addressable Units, Bytes, Cells, Data Types, and Compilers • Different data types may have different cell sizes – i.e., need a different number of bytes to store their representations • A single character needs fewer bytes than does a floating point number, for example • sizeof can be used to tell you how many bytes are required for a given cell (which can be compiler dependent) • sizeof(x) returns the number of bytes required for x, where x can be either a variable name or a type name (like int) • Programmers generally do not need to know how the bytes for a data item like a floating point number are arranged into addressable units inside their cells; that's what compilers are for (to hide the ugly details ;-)

  5. More on Types and Compilers • In C, a statement like float x causes the compiler to do several things, including: • Generate code to obtain some unused storage for use by x whenever it (the float x statement) is executed • Make a note in its internal symbol table so that from now on, whenever the programmer refers to x, the compiler knows what address to use in the machine code it generates

  6. Compilers, Symbol Tables, and Memory Maps reserved unused Here are two C declarations and a simplified example of the compiler's symbol table after it has processed them: compiler's symbol table address type size your code name float w; char z; w 0x4 float 4 z 0x2 char 1 Here's a pictorial representation we'lluse to show part of the compiler's memory map at this point: ••• z w ••• 0x3 0x0 0x1 0x2 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB

  7. Typical Things a Programmer Normally Doesn't Want to Care About • Can we store things like zorw starting at any address? • Why is the address of w0x4 and not 0x5, 0x6, or 0x7? Or will any of the 4 addresses 0x4 through 0x7 work • Compiler writers needs to know that stuff for each kind of hardware they write a compiler for • But an application programmer very rarely needs to know that sort of stuff (again, that's what we have compilers for) ••• z w ••• 0x3 0x0 0x1 0x2 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB

  8. Something the Programmer Sometimes Does Need to Know About (Sort Of) • What is the address of the variableabcanyway? • That's why C provides the ampersand operator, as in&abc • The reason I said “sort of” is that we rarely really care about addresses in and of themselves, we just need to refer to them sometimes • Do you really care about the bit pattern (value) of the address of abcso long as scanf("%f", &abc) works properly? • scanfdoesn't want to know what's currently stored in abc, which is what we'd be telling it if we left out the & and just wrote scanf("%f", abc); it just needs to know where we want it to put the number we're reading in, i.e., the address where we want the user's input stored, or &abc

  9. Could Leaving Out the & in ascanf Call Ever Be Correct? • Sure; for example, if we've declared char string[80]isn't the value of the expression string all by itself already an address (equal to &string[0], in fact) so haven't we already written things like scanf("%s",string)? • Neither scanf nor the hardware care how we compute the address we give them; they want a bit pattern to use as an address, we give them a bit pattern to use as an address; how it's computed (i.e., what expression we evaluated, e.g., string or &string[0]) is not their concern • In the future, we'll be dealing with new types of variables called pointer (or address) variables that actually hold addresses of other variables so if ptrToSomething were such a variable and held the address of some floating point number, scanf("%f",ptrToSomething) might be exactly what we want (but that's a few charts away ;-)

  10. Roadmap Background: Computer memory and addresses The mechanics of pointers: Syntax and semantics Examples of some of the major uses of pointers 

  11. Syntax for Pointer Variables • int*abcdeclares abc to be a variable whose type is pointer-to-integer • In C, the official name of that type isint*, even if that looks a bit odd • The variable abc is not an integer, it is a pointer to an integer • The values stored in abc will be used as addresses and the addresses that can be legally stored there can only be addresses where integers are stored, so if def were an integer variable, abc=&def would be quite proper; but abc=def would not be – and most compilers would complain about it • Reminder: The name of the variable in the declaration above is abc, not *abc; its type is int*, not int

  12. “Typing” in C • C, which is a typed language (unlike Matlab, for example), has still been pretty casual about its numeric types • It has been perfectly happy to let you write sloppy code and have the compiler figure out how to convert back and forth to get the types right for you int x=3; float y=0.0; x=y+2; (a) Convert the integer 2 to floating point (c) Convert the floating point sum back to integer for storage in x (b) Add two floating point numbers With pointer types, it's “no more Mr. Nice Guy”; C is about to get tough on us

  13. Strict Enforcement of Pointer Types int*v; float x; v = x; • The code is not legal in C • Even is not legal • An integer pointer is not an integer, a character pointer is not a character, an integer pointer is not a floating point pointer, etc andC will enforce these differences quite rigorously int*v; inty; v=y;

  14. Some Simple Graphics for Memory Cells 5.25 0x4 w ••• 5.25 ••• 0x3 0x0 0x1 0x2 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB • Remember that each variable is in a cell somewhere and the compiler knows the address of that cell • So after a declaration like float w=5.25we could visualize a portion of the compiler's memory map like so: the human readable form of the binary bit pattern actually stored in the cell But we'll simplify that for use in for our animations here: the programmer's name for the cell w the machine address of the first (lowest) byte in the cell, customarily shown in hex rather than decimal or the more realistic but essentially unreadable binary some cell in memory

  15. Some Simple Graphics for Memory Cells (cont'd) p x q w ??? ??? 0xa76 5.25 0x32e 0x234 0xdab 0xa76 • Here are some C declarations: • And here are the results shown pictorially: float w=5.25, x; float *p; float *q=&w; I'lluse ??? to indicate that the contents of a cell are unknown to us (uninitialized) I just made up totally arbitrary addresses for these cells In general, we'llhave no idea what the addresses are (that's the compiler's job); but whatever the address of this cell w actually is, that will be the bit pattern stored in q q, a pointer variable, contains the address of w, since when we declared q we initialized it to &w

  16. Some Odd But Legal Syntax for the Declaration of Pointers in C p x q w ??? ??? 0xa76 5.25 0x32e 0x234 0xdab 0xa76 • C allows us to do this sort of thing in a single statement: float w=5.25, *p, x, *q=&w; and still get the same results as the multiple statements on the previous slide, namely: • But remember that w and pare of two different types • Even though C let us declare them in the same statement, that does not notnot mean that they are the same type; the type of w is float but the type of p is float*

  17. More Graphics for Memory Cells and Pointers float w=5.25, *q=&w; • Rather than have to deal with those hexadecimal addresses in our pictures, we'll just show arrows to indicate that the contents of a cell are an address that “points” to another cell • But remember: The addresses are the actual reality, they're still there; the arrows are just a graphic to make it easier to see what the addresses actually mean w q 5.25 0xa76 0xa76 0xdab

  18. Sidebar: Inspecting Pointer Values • Vocabulary note: In the software world, the terms “address” and “pointer” are often used interchangeably • You can actually look at address/pointer values if you want to; given the variables declared earlier, try:printf("address of w is %p,q contains %p",&w,q);the 'p' in %pstanding for “pointer”, and it results in a hex print • Want to see them in decimal rather than hex? Replace %p with %d— the real address values are just binary bit patterns anyway, right? • You can print addresses in any format you like; but for a variety of reasons irrelevant to us here, it's customary to use hex for talking about addresses and it's customary in your code to highlight the fact that you know the thing being printed out is an address (pointer) by using %prather than %x

  19. So How Can We Use Pointer Variables?(Still “How”, Not “Why”, Be Patient) • We can use pointer variables in the same ways we use any other variables; specifically, we can: • Set them equal to the value of an expression, provided it's of the correct type, i.e., an address (pointer value) of the correct type, as when we set q=&w on an earlier slide • Evaluate them in conditionals such as if's or while's, provided they are being compared to expressions of the correct type; e.g., if q and p are both pointer variables of the same type, we can ask if (q==p) ... , which asks whether or not they are they pointing to same cell • We can even use them in arithmetic expressions to do our own array-address arithmetic, but we'll leave that discussion for another day

  20. *De-Referencing But there's one thing more that we can do with pointers (and not with any other type of value) and that's the operation known as “de-referencing” and it's the key to a wonderful new world

  21. To De-Reference Is to Follow a Pointer • Let's start from float w=5.25, x, *q=&w; w x q 5.25 5.25 ??? x=*q x=q is not legal, but is and the result would be to set x to contain 5.25 Note that x=*q did not store the contents of q in x; instead, we de-referencedq The*there (in the x=*q) is the de-referencing operator and it means that the value of the expression *q is not the value stored in q, but the value stored where qpoints– e.g., the value of the expression *q is 5.25

  22. Sidebar on the Meaning of in Declarative vs Imperative Statements '*' • In a declarative statement like char z,*y the '*'is part of the type name – the type of y there is char* • In an imperative statement like x=*y; the '*'is the dereferencing operator • These two uses of the asterisk are different; they are obviously related, since only pointers can be de-referenced, but they are nonetheless distinct

  23. More Complicated Expressions with De-Referencing • Starting from float w=5.25, x, *q=&w;we can do things like: x=-1.25+(*q) which is legal and stores 4.00 in x, and could even have been written without the parentheses asx=-1.25+*q although stylistically I like the first version a lot better • A compiler can even figure out that 2.0**q must mean 2.0*(*q), since there's no other meaning for **in C, so that too (2.0**q) is a legal expression, having a value of 10.5, although it's not particularly readable and hence seems poor style to me • And so on; *qis just an expression; it gets evaluated to produce a value – a floating point value, in this particular example – and can be used anywhere any other floating point expression or value could be used

  24. The De-Referencing Operator on the Left Side of an Assignment Operator • Let's start from float w=5.25, *q=&w;and do: *q=3.14; w q 3.14 5.25 That's legal and has the result of storing 3.14 in the cell whose name is w, replacing the 5.25 that we started with Note thatq itself wasn't the target or destination for the storage of a value by an assignment operation; instead, we stored something in the cell pointed to by q Again, we de-referencedq, but this time on the left side of an assignment operator

  25. Potential Danger with the De-Referencing Operator • Look at what will happen if these two statements are executed: float *p; *p=3.14; • When we execute the second statement, *p=3.14, one of two things is going to happen, neither of them good: • If the unknown (un-initialized) bit pattern stored in p is not a legal address for us to use, the operating system will throw our program totally off the computer with a nasty error message like, “segmentation error, core dumped” or possibly “bus error” • Perhaps worse, if the unknown address in p happens to be legal, we'll actually store 3.14 somewhere, overwriting data that may have been important (like a password, perhaps?), and we'll never know it until our program malfunctions later p Note that p has not been initialized ???

  26. The NULL Pointer • The second problem from the previous slide, a delayed malfunction, is probably the worse – it's usually better to have a program die immediately than unknowingly give possibly erroneous answers for an unknown length of time and then die mysteriously while executing statements far away from the ones that really caused the problem • The problem came about, remember, because we declared a pointer variable and didn't initialize it – usually a bad habit with variables of any sort • The point: There is a special pointer value that has several uses in C; it is the symbolic constant NULL– and remember that capitalization matters in C

  27. The NULL Pointer (cont'd) • NULLmeans “nowhere” or “officially undefined”, which is quite different from my habit of using ??? as pseudo-code to mean “unknown” (??? is not a legal symbol in C) • The problem with an unknown pointer is that it may be perfectly valid but pointing someplace very bad for us • NULL is a known value (its bit pattern can vary from machine to machine or even compiler to compiler), but any attempt to de-reference a NULL pointer is invalid and will cause the operating system to terminate your program • You can use NULL in conditional expressions like so: if (a_ptr!=NULL) ... and checking this way before de-referencing a pointer is a good programming practice

  28. The NULL Pointer (cont'd) In general, C compilers don't automatically initialize variables for you – e.g., after int x, we have no idea what value is stored in x – nor do they check for the use of uninitialized variables – e,g., int x, y=x+5;is unfortunately legal and (depending on the compiler) won't even generate a warning Pointer variables are an exception; most modern compilers initialize pointers variables to NULL for you if you don't supply some other initial value yourself I myself tend to make it explicit anyway (e,g., int*q=NULL) just to be safe and to let anyone reading my code know that I've explicitly thought about what values my variables should be initialized to

  29. Graphics for Copying Pointers w q x • Givenfloat w, *q=&w, *x; • When we set x=q, we copy 0xa76, the value stored in q, into x, justas we do for assignment of any value to a variable – note that there's no de-referencing on either side there • But what we'll show in animations is just copying the arrow • For our illustrations here, we'll let the arrow head hitting anywhere on a cell mean that it's pointing to (contains the start address of) that cell, so the shape and routing of the arrows in our diagrams doesn't matter; only the cell touched by the arrowhead matters • That graphic, above, then shows that the contents of x and q are equal, since they point to the same place, even though the arrows look a bit different as artwork ??? ??? 0xa76 0xa76 0xa76

  30. Insanity Check Before Moving on to the Really Good Stuff a b 2 • Think you're getting the hang of this, huh? OK, try this: Let's start from just int a=2, *b=&a; • Now consider *b*=*b**b; Is it legal, and if so, what changes in the picture up above and how? • Do I think you should write code like this? Good grief, no; but in fact it is legal and you need to be able to figure such things out since, there are, unfortunately, idiots around who do sometimes write code like that • The answer, by the way, is that that expression sets a to 8, parentheses make it slightly clearer: (*b)*=(*b)*(*b) but the compiler will buy it even without the parentheses

  31. Key Pointer Points to Remember(Sorry, Couldn't Resist ;-) • Pointers are just bit patterns (as are all values in C) • Pointer variables are assigned cells (as are all variables in C) • A pointer has a type (as must all variables and values in C) • A pointer's type determines the type of the cells it's allowed to point to – e.g., an integer pointer cannot contain the address of a floating point number • C is stricter about type enforcement with pointers than with its numeric types

  32. Key Points to Remember (cont'd) • You can store values into pointer variables themselves (not de-referencing them) with an assignment statement, the same ways you store any other value in the appropriate type of variable, e.g., int x, *y, *z; y=&x; z=y; • You can ask questions about the values stored in pointer variables themselves (again, not de-referencing) the same ways you ask questions about other values in other types of variables, e.g., if(y==&x&&z!=NULL)… Remember: The type of of this expression must match the type of the pointer variable y and eventually we'll be dealing with pointer-valued expressions more complicated than simply &x We could for example, use a function that returned a pointer and so we might want to set y=funtionA(…) but only if funtionAreturned an integer pointer; if it returned a character pointer, the compiler would balk

  33. Key Points to Remember: De-Referencing • When you do de-reference a pointer you're saying: “Whatever you're trying to do, don't do it to me, the pointer variable, do it to whatever it is I'm pointing to” • To de-reference a pointer variable, put an * in front of its name (the * is the de-referencing operator)

  34. Key Points to Remember (Summary) • Syntactically, pointers look and feel just like other variables • They can appear in expressions in the same ways other variables do, including • On the left side of the assignment operator = • In expressions used as conditionals (e.g., if(...)statements) although C is stricter about enforcing type compatibility in expressions with pointers than with numeric types • It's the semantics of de-referencing that makes pointer variables “special” and different from numeric variables: only pointer values can be de-referenced • Note: Since they don't look any different from other variables syntactically, it's a good idea to use some naming convention to make it easier to spot them later on, e.g., int *a_ptr

  35. Roadmap Background: Computer memory and addresses The mechanics of pointers (syntax and semantics) Examples of some of the major uses of pointers Functions with deliberate side-effects Dynamically linked data structures 

  36. The Real Benefits of Pointers(You've Been Very Patient) • The important uses of pointers in C rarely involve writing things like int x,*y=&x; where we are setting up *y to be what is known as an “alias” for x; why should we bother when we already have a perfectly useful name for x? • We did that earlier just to illustrate how pointers actually work – although the code we wrote was, in fact, legal, it was pretty pointless (so to speak ;-) • Instead of silly aliases, the real uses of pointers include: • Writing functions with side effects • Building dynamically linked data structures

  37. Writing Functions That Produce Side Effects • As we have already seen this semester, changing the value stored in a local variable inside a function has absolutely no effect on anything outside the function • Even if the local variable or parameter has the same name as another variable defined outside the function – which is a baaad programming practice! – there is absolutely no relationship between them since they have different scope • But sometime we may want one function to change the value stored in a variable defined in another function (e.g., scanf) • That's called “creating a side effect” (I'll explain why later) and it requires using pointer variables

  38. Review of Passing Argument Values into Functions in C param1 Remember: the only way C passes argument values into functions is by copying them (formally known as pass-by-value) ...and the resultant value is copied into the cell of the parameter corresponding by position to the argument that just got evaluated – i.e., the value of the first argument is copied into the cell for the first parameter, the value of the second argument into the cell for the second parameter, and so on int funct1(int param1) { /* function body */ } When it compiles a function definition, the compiler generates code that causes each separate execution of the function to request new cells for the temporary storage of the function's parameters before the statements in the body of the definition start executing After all the arguments have been evaluated and the resultant values copied into the corresponding parameter cells, then the statements inside the body of the function get executed Some irrelevant jargon: evaluating arguments and copying their values into parameters is known as “binding” arguments to parameters; binding is part of what is known as the “activation” of a function After the function's execution has completed (any explicit return statement is executed or when the execution flow hits the '}'at the end of the function definition) … … the returned value (if the function is not of type void) is substituted for the expression consisting of the function call (the name followed by the argument list in parentheses) … ... the expression for each argument in the argument list of the function call is then evaluated ... So each time this function call (or “invocation” or “activation”) of funct1 is executed ... ... a temporary integer cell gets created/allocated int main() { int x; while (…) x = funct1( ) ... } …and all storage local to the function is destroyed (unless the programmer has explicitly declared that it is to be static storage and hence not to be destroyed) 72 36*2

  39. Passing Pointer Values (Addresses) as Arguments to a Function • The compiler's mechanism for passing a pointer value into a function is exactly the same as for any other type of value: • When the function call is executed, a parameter cell to hold a pointer value is created • An argument gets evaluated to yield a value • The resultant value (an address, which we illustrate by an arrow, but it's really just a bit pattern like any other value) gets copied into the correct parameter cell • But what the programmer can do with a copied address/pointer value (i.e., de-reference it!) makes for some powerful new programming capabilities

  40. Passing Pointer Values (Addresses) as Arguments to a Function (cont'd) param1 x • • • • • • Note that what's stored here is in reality just a bit pattern, not anything symbolic like '&x' Names like 'x' and 'funct1' are part of the programmer's communication with the compiler; they don't exist in the compiled code – the executable program output by the compiler So even if there were a local variable named x here in funct1 (and that's a very bad programming practice, since it makes the code potentially quite confusing) this cell would contain the bit pattern for the address for the x back in the main function The compiler's mechanism for passing a pointer value into a function is exactly the same as for any other type of value ... the value in main's x is changed; so funct1 has produced a side-effect When this statement gets executed ... Now when this statement gets executed ... int main() { int x=5; ... funct1(&x) ... } int funct1(int *param1) { *param1=17; } 5 17 ... this cell gets created and initialized ...so this cell now contains the address of (points to) the cell named 'x'back in the main function ... and its value is an address, or pointer value, pointing to this cell ...into this cell... ... then this argument gets evaluated ... Whenever this function call gets executed ... This address (pointer) value is then copied ... ... this temporary integer pointer cell gets created …

  41. Summary of Values and Side Effects • It's called a side-effect because the original “purist” view of functions came from mathematics, where sin(x) is just a mathematical expression designating a value, not a programming entity that might actually do something • A “pure” function in C just computes and returns a value but doesn't affect anything outside of itself during its computation (i.e., it has no side effects) • Side effects in the calling function occur only if you specifically program for them using pointers; but the mechanism for passing pointer/address values as arguments to a function is the same as for passing any other kind of value

  42. Summary of Programming for Side Effects • To make a function able to change a variable declared in a function that calls it: • The calling function must supply the address of the variable it wants changed as an argument to the function call • The called function must: • Have a parameter of the correct pointer type to receive the address argument it's supposed to change • Dereference that parameter on the left side of an assignment operator to make the change back in the calling function int main() { int x; ... funct1(&x) ... } int funct1(int *param1) { *param1=... ; }

  43. Summary of Values and Side Effects (cont'd) • Don't be confused by the jargon: sometimes a side-effect is the whole point of the function, e.g., scanf, which we want to read some keyboard input, convert the ASCII codes of the user's keystrokes into some more useful form (like a floating point number), and store the converted value not in a variable local to the scanf but in a variable declared in the function that calls it; which is, by definition, a side-effect, even though it's the whole point of the scanf function in the first place • Remember: the purpose of a function can be to compute and return a value or produce side effects, or both

  44. Sidebar: “Pass-by-Reference” • Other languages have special syntax that explicitly highlights“pass-by-reference” to allow a function to change variables declared in other functions • Some textbook authors (who really should know better) say that C supports both “pass-by-value” and “pass-by-reference” • Technically that is incorrect: the only argument/parameter binding mechanism supported by C is “pass-by-value”; perhaps it should have been called “pass-by-copying”, but it wasn't (hey, it's not my fault!) • But since C provides an explicit de-referencing operator (many languages do not), a “passed-by-value” copy of an address value (i.e., a pointer) can be de-referenced to achieve the same side effect as if the original variable had been “passed-by-reference” • Some textbooks call that “simulating” pass-by-reference

  45. Roadmap • Background: Computer memory and addresses • The mechanics of pointers (syntax and semantics) • Examples of some of the major uses of pointers • Functions with deliberate side effects • Dynamically linked data structures • Introduction • Mechanics • Detailed Example 

  46. Dynamically Linked Data Structures • Suppose we want to write a program that works with a set of numbers but there's no way to know ahead of time how many numbers it will process, so we can't efficiently declare an array to hold them – perhaps operators input the numbers one at a time until they get tired and tell our program “no more” • If our code declared too big of an array size, most of the time we'd be wasting most of it • But if we declared too small an array and filled it up, we couldn't keep going without major problems • A dynamic data structure whose size can increase one cell at a time whenever we want it to is what we need • A linked list implemented with pointers is an important technique for implementing such a dynamic data structure

  47. Dynamically Growing a Linked List We'llneed a pointer to the start of our list; it should be appropriately named; for this example, we'll be stunningly original and call it “start” Initially, before the operator provides any input numbers, the list is empty A pointer value of NULLis a standard way to indicate the end of the list; so if the start is NULL, (pointing nowhere) that means the list is empty A NULL pointer is typically shown graphically by an arrow pointing to ground – that's the electrical engineer's symbol for a ground there, the start When we get a number, we then dynamically obtain some storage space for it and link it into the list Let's not worry just yet about how we get new storage dynamically; all will be revealed in time 18 -2 461 23 314 • And so on ... • Notice that the structures in the list have no names; they can only be accessed via some pointer (we'lltalk more about this later, obviously) • Variable names are part of the programmer's communication with the compiler; in C, they normally don't exist in the executable version of the program (which only deals with machine addresses) • Well, our compiler is long gone when these new cells are dynamically created during our program's execution; they can't possibly have names The next time we get a new number, we again get some new space for it and link it in to the end of the growing list Note that the list elements are not simple integer cells but structures of some sort, since each must have space for a pointer in it as well as the integer

  48. OK, That Was the Basics;Now to the Gory Details • The only brand new concept we need to be able to actually do what we just saw in the animation is a method for dynamically obtaining new storage space from the operating system: the pre-defined function malloc, for memory allocation • We'll also need to exploit the capabilities of things we already know but in new, surprisingly powerful ways: • Recursive structures • Access to unnamed structures and their components/fields

  49. Roadmap • Background: Computer memory and addresses • The mechanics of pointers (syntax and semantics) • Examples of some of the major uses of pointers • Functions with deliberate side effects • Dynamically linked data structures • Introduction • The mechanics • malloc • Recursive structures • Access to components of unnamed structures • Detailed example 

  50. Obtaining New Memory withmalloc • From the programmer's point of view, malloc is pretty simple • Here's malloc in action: some_ptr=malloc(40); doing 2 things: • Obtaining new memory from the operating system; the amount of memory to be obtained is specified by the value of its argument, 40 bytes, in this example • Returning, as the value of the expression malloc(40), the address of the new memory (a pointer value, in other words) • Note that malloc is being used both for value and for side-effect — getting the new memory is its (crucial!) side effect, and the address of that memory is its returned value

More Related