DOC PREVIEW
UW CSE 303 - Lecture Notes

This preview shows page 1-2-3-4 out of 11 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 11 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

'&$%CSE 303:Concepts and Tools for Software DevelopmentDan GrossmanSpring 2005Lecture 9— C: structs, heap-allocation, initialization, memorymanagementDan Grossman CSE303 Spring 2005, Lecture 9 1'&$%Where are WeWe are learning C, a lower-level and less-safe language than Java Sofar:• Basic control constructs• Left vs. right expressions• The address-of (&) and dereference (*) operators• Some strange rules for arraysToday:• structs• memory management• initializationLater: header files, the preprocessor, printf, casts, function pointers,gotchasDan Grossman CSE303 Spring 2005, Lecture 9 2'&$%From last time...A couple points that got lost in the shuffle:• Dangling pointers and lifetime vs. scope• Declarations should precede usesDan Grossman CSE303 Spring 2005, Lecture 9 3'&$%Dangling Pointersint* f(int x) {int *p;if(x) {int y = 3;p = &x; /* ok */} /* ok, but p now dangling *//* y = 4 does not compile */*p = 7; /* YPMSTCOF, but probably not */return p; /* uh-oh */}void g(int *p) { *p = 123; }void h() {g(f(7)); /* YPMSTCOF, and likely a problem */}Dan Grossman CSE303 Spring 2005, Lecture 9 4'&$%No forward references• A function must be defined and/or declared before it is used.(Lying: “implicit declaration” warnings, return type assumed to beint, ...)• You get a linker error if something is declared but never defined(or main is not defined).• You can still write mutually recursive functions, you just nee d adeclaration.Dan Grossman CSE303 Spring 2005, Lecture 9 5'&$%StructsA struct is a record.A pointer to a struct is like a Java object with no methods.x.f is for fie ld acces s.(*x).f in C is like x.f in Java.x->f is an abbreviation for (*x).f.There is a huge difference between passing or assigning a struct andpassing or assigning a pointer to a struct.Again, left-expressions evaluate to locations (which can be wholestruct locations or just field locations).Again, right-expressions evaluate to values (which can be whole structsor just fields).Dan Grossman CSE303 Spring 2005, Lecture 9 6'&$%Heap-AllocationSo far, all of our ints, pointers, arrays, and structs have beenstack-allocated, which in C has two huge limitations:• The space is reclaimed when the allocating function returns• The space required must be a constant (only an issue for arrays)Heap-allocation has neither limitation.Comparison: new C(...) in Java:• Allocate space for a C (exception if out-of-memory)• Initialize the fields to null or 0• Call the user-written constructor function• Return a reference (hey, a pointer!) to the new object.In C, these steps are almost all separated.Dan Grossman CSE303 Spring 2005, Lecture 9 7'&$%Malloc, part 1malloc is “just” a library function: it takes a number, heap-allocatesthat many bytes and returns a pointer to the newly-allocated memory.• Returns NULL on failure.• Does not initialize the memory.• You must cast the result to the pointer type you want.• You do not know how much space different values need!Do not do things like (struct Foo*)(malloc(8))!Dan Grossman CSE303 Spring 2005, Lecture 9 8'&$%Malloc, part 2malloc is “always” used in a specific way:(t*)malloc(e * sizeof(t))Returns a pointer to memory large enough to hold an array of length ewith elements of type t.It is still not initialized (use a loop)!Underused friend: calloc (takes e and sizeof(t) as separatearguments, initializes everything to 0).Dan Grossman CSE303 Spring 2005, Lecture 9 9'&$%Half the BattleWe c an now allocate memory of any size and have it “live” forever.For example, we can allocate an array and return it.Unfortunately, computers do not have infinite me mory so “livingforever” could be a problem.Java solution: Conceptually objects live forever, but the syste m has agarbage collector that finds unreachable objects and reclaims theirspace.C solution: You explicitly free an object’s space by passing a pointerto it to the library function free.Freeing heap mem ory correctly is very hard in complex software and isthe disadvantage of C-style heap-allocation.• Later we will le arn idioms that help. For now just learn the rulesof the game.Dan Grossman CSE303 Spring 2005, Lecture 9 10'&$%Everybody wants to be free(d once)int * p = malloc(sizeof(int));int * p = NULL; /* LEAK! */int * q = malloc(sizeof(int));free(q);free(q); /* YPMSTCOF */int * r = malloc(sizeof(int));free(r);int * s = malloc(sizeof(int));*s = 19;*r = 17; /* YPMSTCOF, but maybe *s==17 ?! */Problems much worse with functions:f returns a pointer; (when) should f’s caller free the pointed-to object?g takes two pointers and frees one pointed-to object. Can the otherpointer be dereferenced?Dan Grossman CSE303 Spring 2005, Lecture 9


View Full Document

UW CSE 303 - Lecture Notes

Documents in this Course
Profiling

Profiling

11 pages

Profiling

Profiling

22 pages

Profiling

Profiling

11 pages

Testing

Testing

12 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?