Unformatted text preview:

1CMSC 212 – F07 (lect 09)Announcementsz Exam #1 –March 8th(6:00 PM), Room Armory 0126z Reading– Chapter 112CMSC 212 – F07 (lect 09)Pointers and Functions (cont)int *foo3(int *a, int *b){if (*a > *b ) {return a;} else {return b;}}int *foo4(int a, int b){if (a > b ) {return &a;} else {return &b;}}3CMSC 212 – F07 (lect 09)Dangling Referencez Problem: Stack variables go out of scope on returnz Consider:int *foo() {int x = 42;return (&x);}int *ptr;ptr = foo();4CMSC 212 – F07 (lect 09)Multidimensional Arraysz int matrix[3][4];– C uses arrays of arrays to handle multidimensional arrays– This is an array of 3 elements, each containing 4 integersz Storage Order– row major order– right most dimension has adjacent elements in consecutive memoryz Subscripts– matrix+1 is the second group of 4 int elements5CMSC 212 – F07 (lect 09)Pointers To Arraysz int vector[10], *vp=vector;– vp points to the array of 10 integersz int matrix[3][10], *mp = matrix;– ERROR: mp points to an array of ints, but matrix is an array of arraysz Can also treat multi-dimensional arrays as single– int *pi = &matrix[0][0] – int *pi = matrix[0]– advancing pi (pi++) will navigate entire array of arrays6CMSC 212 – F07 (lect 09)Passing Multidimensional Arraysz Passed as base address of first element– compiler needs help to know what dimension arez Example:int matrix[3][10];func2(matrix);void func2(int (*mat)[10]); /* 10 elements in 2nd array */void func2(int mat[][10]); /* same as above */z Rule– need to define size for all but first array in multidimensional arrays7CMSC 212 – F07 (lect 09)Type Conversionz C lets you assign variables of different types– called type conversion– useful when dealing with• external devices– int *fooDev = (int *) 100;– we know the foo device is at location 100• when type information read from a file is based on file contents.z WARNING: This can be very dangerous– DON’T DO ITz (type *) variable:–int*x;– float *y;–x = (int*) y;8CMSC 212 – F07 (lect 09)Stack and Heap Memoryz Stack Memory– Allocated and de-allocated in a specific order• last allocated is the first to be freed– Useful for representing program local variablesz Heap Memory– Can allocate and de-allocate in any orderStack TopFree SpaceAllocated Space9CMSC 212 – F07 (lect 09)Dynamic Memoryz Why Dynamic Memory– Eliminate Compile Time Limits• hard to get sizes of things exactly right• over estimation leads to wasted spacez User Managed Heap vs. Garbage Collection– Garbage Collection• Don't need to worry about de-allocation• Takes times to run collection algorithms– User Managed• Control precisely when to de-allocate an object• Can create errors if de-allocate a object still in use10CMSC 212 – F07 (lect 09)Heap Memory Managementz Allocating memory:– void *malloc(size_t requestedSize);• allocate requestedSize bytes of memory• no initialization of that memory space– void *calloc(size_t requestCount, size_t objectSize);• allocate requestCount objects of size objectSize bytes each• set the requested memory to zeroz Type Information– malloc/calloc both return void *– need to convert to desired type using cast operator11CMSC 212 – F07 (lect 09)Memory Deallocationz free(void *p);– returns space pointed to by p– does not change p• good idea p=NULL; right after deallocation.z Using Free– always free memory when done with it– free releases the space• it does not change that space’s value• it does not change the value of the pointer– Never dereference a pointer after free is called:• free(p);• if (*p) { …} /* error, pointer is no longer valid */12CMSC 212 – F07 (lect 09)Pointer Aliases & Freez If two pointers point to the same thing– Freeing either ones, frees the underlying storageint *p, *q;p = (int *) malloc(sizeof(int);q = p;free(p);if (*q) { … } /* error: *q points to freed space */qp13CMSC 212 – F07 (lect 09)Common Dynamic Memory Errorsz Dereferencing pointers that have random value– int *x, y=3;– printf(“%d %d\n”, y, *x);z Dereferencing NULL pointers– int *foo = NULL;– *foo = 3; /* ERROR */z Forgetting to check return value of malloc/callocz Using malloc and not initializing valuesz Not allocating enough space– very common with stringschar name1[] = “Jan”;char *name2;name2 = malloc(sizeof(name1)); /*should be (strlen(name1)+1)strcpy(name2,name1);z Going past end of allocated space– very easy when using array syntax and loopsint *myInts;/* allocating space for k integers and testing return of calloc */for (i=0; i <= k; i++) {myInts[i] = anotherFunc(i, k);}14CMSC 212 – F07 (lect 09)More Common Memory Errorsz Calling Free on something not from heapint *ptr; j;j = 3;ptr = &j;free(ptr); /* ERROR: ptr doe not point to something in heap */z Calling Free on other than the start of allocationint *ptr;ptr = calloc(sizeof(int), 10);free (ptr + 3);z Using memory that has been freedT *curr;free (curr);curr = curr->next; /* ERROR: curr has already been freed */15CMSC 212 – F07 (lect 09)Memory Leaksz Common problem to forget to free memory– Doesn't cause the program to crash (at first)– Wastes memory and can cause the program to slow downz Example:– int *myInts;– myInts = malloc(100);–….– myInts = malloc(200); */ now leaked 100 bytes */16CMSC 212 – F07 (lect 09)Const Keyword and Pointersz const int *p;– pointer to an integer that doesn't change:– const x = 42;– p = &x; /* legal */– *p = 20; /* illegal - changing the constant */z int *const p;– constant pointer to an integer;– int *const p = &foo;– *p = 42; /* ok: just changing the value */– p = &bar; /* illegal: changing the pointer */17CMSC 212 – F07 (lect 09)Blocks of Memoryz C supports operations on blocks of memory– might be an array, a struct, an array of structs, etc.z Copying– void *memcpy(void *dest, const void *src, size_t len);• copies memory pointed to by src to memory pointed to by dest• copies len bytes of memory• returns the value of src– void *memmove(void *dest, const void *src, size_t len);• copies memory pointed to by src to memory pointed to by dest• copies len bytes of memory• returns the value of src• handles the case if dest and src overlap18CMSC 212 – F07 (lect 09)What if you need more memory?z Could– malloc new space– copy data from old space to new– free old spacez C provides a short cut– void *realloc(void *ptr, size_t new_size);– allocates new space


View Full Document

UMD CMSC 212 - Lecture Slides

Download Lecture Slides
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 Slides 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 Slides 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?