Docsity

CMSC 212 Lecture 9: Pointers and Memory Management, Study notes of Computer Science

Partial preview of the text

Download CMSC 212 Lecture 9: Pointers and Memory Management and more Study notes Computer Science in PDF only on Docsity!

Announcements

l^ Program #1B– Due Today– Midterm #1 is next Tuesday l^ Reading– Chapter 6 (today)– Chapter 11 (next Tuesday)

Pointers

l^ Can declare any variable to be of type pointer– are similar to references in Java– use * before variable name to create a pointer to the type

  • int *foo;• myTypeDef *myPtr;• float *bar;– The type determines both:• what is pointed to• the size of the object being pointed to

l^ Initialization– creating a pointer doesn't create the space it points to– int *foo;– foo = 3; / error: haven't defined what it points to */

Other Pointer Declarations

l^ Can declare a pointer to a pointer– int **p;

/* p pointer to a variable that points to an int */

– useful if you want to modify a pointer in a subroutine l What declaration:– int *p, q;– declares p as a pointer to an integer and q as an integer l Typedefs of pointers improve readability– typdef int *intPtr;– intPtr p, q;

Pointer Assignments

l^ Pointers a normal variables– they are not initialized unless assigned l^ Sample Assignments:– int *p, *q, i1, i2;– p = &i1;

/* p now points to i1 */

  • q = p;

/* q now points to i1 too */

  • p = &i2;

/* p now points to i2 */

  • *p = *q;

/* the value of i1 is copied to i2 */

NULL Pointer

l^ NULL is a pointer to nothing– (void *) 0 is its type– defined in stdlib.h l^ Can be used to initialize pointers– int *p;– p = NULL; l^ Can be used in comparison– if (p != NULL) {

l^ Often returned by functions to indicate error

Pointer Examples

size_t strlen(char *str){ size_t length;for (length=0; *str != '\0'; str++) {length++;} }

Const Keyword and Pointers

l^ const int *p;– pointer to an integer that doesn't change:– const x = 42;– p = &x;

/* legal */

  • *p = 20;

/* illegal - changing the constant */

l^ 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 */

Pointer Aliases

l^ Sometimes two pointers point to the same thing– This can be useful– This can cause problems:

int *p, q;int a= 89;p = &a;q = p;free(p);if (q) { … }

/* error: *q points to freed space */

89

q

p

a

Pointers and Functions

l^ Parameters– can use const to prevent functions from changing valuesint frob(const char *data, int size) {

if (data[0] == 'Q') { .. }

/* OK: just using the data */

data[2] = 42

/* Error: can't modify data */

} l Functions can return pointer typesint *getStuff(int *a, b) {if (a > *b ) {return a;} else {return b;} }

Dangling Reference

l^ Problem: Stack variables go out of scope on return l^ Consider:int *foo() {

int x = 42;return (&x);}