CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Similar documents
CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Dynamic Data Structures. CSCI 112: Programming in C

In Java we have the keyword null, which is the value of an uninitialized reference type

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

CS24 Week 2 Lecture 1

Kurt Schmidt. October 30, 2018

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Arrays and Pointers. CSE 2031 Fall November 11, 2013

C Structures & Dynamic Memory Management

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

CS 11 C track: lecture 5

Arrays and Pointers (part 1)

CS61, Fall 2012 Section 2 Notes

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Class Information ANNOUCEMENTS

Lecture 8 Dynamic Memory Allocation

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Programs in memory. The layout of memory is roughly:

Memory Allocation. General Questions

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Arrays and Memory Management

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space

Heap Arrays and Linked Lists. Steven R. Bagley

Arrays and Pointers (part 1)

Recitation #11 Malloc Lab. November 7th, 2017

CS61C : Machine Structures

First of all, it is a variable, just like other variables you studied

Fall 2018 Discussion 2: September 3, 2018

MPATE-GE 2618: C Programming for Music Technology. Unit 5.1

Dynamic Memory Allocation

Heap Arrays. Steven R. Bagley

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

CSC C69: OPERATING SYSTEMS

CS61C Midterm Review on C & Memory Management

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CA31-1K DIS. Pointers. TA: You Lu

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

BBM 201 DATA STRUCTURES

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

DAY 3. CS3600, Northeastern University. Alan Mislove

Contents of Lecture 3

CS349/SE382 A1 C Programming Tutorial

Lecture 04 Introduction to pointers

Lectures 13 & 14. memory management

How about them A s!! Go Oaktown!! CS61C - Machine Structures. Lecture 4 C Structures Memory Management Dan Garcia.

POINTER AND ARRAY SUNU WIBIRAMA

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

Arrays and Pointers in C. Alan L. Cox

Intermediate Programming, Spring 2017*

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

Memory Management. CSC215 Lecture

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Dynamic Memory Management

ECE 15B COMPUTER ORGANIZATION

CSC 1600 Memory Layout for Unix Processes"

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

CS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models

Dynamic Memory CMSC 104 Spring 2014, Section 02, Lecture 24 Jason Tang

Dynamic Allocation of Memory

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

Pointers, Arrays, Memory: AKA the cause of those Segfaults

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0)

CS 222: Pointers and Manual Memory Management

EL2310 Scientific Programming

Data Structure Series

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Section Notes - Week 1 (9/17)

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

CS61C : Machine Structures

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

SYSC 2006 C Winter 2012

Lectures 5-6: Introduction to C

Binghamton University. CS-211 Fall Dynamic Memory

11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS61C : Machine Structures

CSC231 C Tutorial Fall 2018 Introduction to C

Dynamic Memory Management

C PROGRAMMING Lecture 5. 1st semester

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

o Code, executable, and process o Main memory vs. virtual memory

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CS61C : Machine Structures

CS201 Some Important Definitions

Programming. Pointers, Multi-dimensional Arrays and Memory Management

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Advanced Pointer Topics

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Transcription:

CS113: Lecture 9 Topics: Dynamic Allocation Dynamic Data Structures 1

What s wrong with this? char *big_array( char fill ) { char a[1000]; int i; for( i = 0; i < 1000; i++ ) a[i] = fill; return a; void main() { char *b; b = big_array( z ); It s the usual thing: the activation record for big_array gets destroyed after the function returns, so b isn t pointing to anything stable. 2

But what about dynamic allocation? Remember the good old days of Java programming? If you want, say, a new Vector, you just use the new operator to create one! When you have it you can fill it with as much crap as you want. The following Java code works just fine: Vector getvector() { return new Vector(); void main() { Vector v = getvector(); /* do stuff with the vector */ Why does this work? Storage space for objects is allocated dynamically, outside of the activation record. Within a function, the activation record keeps a pointer to the dynamic object. (You ve been using pointers all this time!) When you re done with an object, the Java VM determines this and garbage collects the memory. 3

The Heap C lets you allocate memory dynamically too, but it s all explicitly controlled by the programmer. Dynamic memory is stored outside of the activtion records for functions, in a memory area called the heap : foo() int int* 13 bar() mystruct* int array foo() int 17 int* mystruct main() 3.14 float The Heap The Execution Stack 4

Your keys to the heap: malloc and free Use malloc (for memory allocate ) to allocate memory in the heap. malloc() takes an unsigned integer representing the number of bytes to allocate It has type (void*), so you must cast it to another pointer type before using it When you re done with the memory, use free to free up the memory space in the heap. free takes a pointer to a chunk of memory freed by malloc K & R say: it is a ghastly error to free something not obtained by calling malloc 5

The fixed program The paradigm: allocate the memory, check to make sure it worked, use it, then free up the memory. char *big_array( char fill ) { char *a; int i; a = (char *) malloc( sizeof(char) * 1000 ); /* Don t forget to check if it s null! */ if( a == NULL ) return a; for( i = 0; i < 1000; i++ ) a[i] = fill; return a; void main() { char *b; b = big_array( z ); /* do something with b */ free( b ); 6

The Stack and the Heap big_array() activation record fill a z z z z main() activation record b z char* memory When big_array finishes its activation record is destroyed, but it returns (to b) a pointer to the new array in the heap. You can (and should) think of the heap as a big array of indeterminate type, with static extent. 7

A more flexible version The following function lets us make arrays of any size we want! char *big_array( char fill, int size ) { char *a; a = (char *) malloc( sizeof(char) * size ); if( a == NULL ) return a; for( i = 0; i < size; i++ ) a[i] = fill; return a; Always check that a pointer is not NULL before dereferencing! 8

Dangling pointers Always keep track of whether dynamically allocated memory pointed to by some pointer is still valid. void main(void) { int *array; array = (int *)malloc(1000*sizeof(int)); if( array!= NULL ) { /* Do stuff */ free(array);... printf("number: %d\n", array[5]);... 9

malloc s cousins malloc() returns a pointer to a memory location in the heap of a given size, but the contents of that memory may be filled with garbage. calloc() returns pointer memory that is guaranteed to be zeroed: Slightly different calling sequence, e.g. intptr = (int *) calloc(1000, sizeof(int)); If you need more memory than you first allocated, use realloc: intptr = (int *) malloc(1000 * sizeof(int));... intptr2 = (int *) realloc( intptr, 5000 * sizeof(int));... realloc first tries to expand the memory pointed to in the heap in place, then tries to find more space elsewhere in the heap. If success, sets pointer to new memory location (e.g. intptr above), frees old memory if necessary, and returns pointer to new memory location (intptr2). If failure, leaves original pointer and memory unchanged, returns NULL. 10

What good is this malloc thing? Suppose you want to write a program which stores names (of people) along with their addresses. One way to implement would be to define a struct holding all of this information, and then define an array of structs at the beginning of the program: struct person_struct { char name[30]; char address[60]; ; struct person_struct database[6000]; Difficulties: Need to know ahead of time the maximum size of the database. If the maximum size is 6000 and only 50 people stored, much memory is wasted. 11

A naive implementation struct person_struct { char name[30]; char address[60]; ; struct database_struct { struct person_struct people[100]; int num_people; ; void add_person( struct database_struct *db, char *pname, char *add ) { strcpy( (db->people[db->num_people]).name, pname ); strcpy( (db->people[db->num_people]).address, add ); (db->num_people)++; void main() { struct database_struct db; db.num_people = 0; add_person( &db, "Sherwood, Erik", "1234 Street Ave., Ithaca, NY 14850" ); 12

Linked list implementation #include <stdio.h> #define NAME_SIZE 30 #define ADD_SIZE 60 struct list_item_struct { char name[name_size]; char address[add_size]; struct list_item_struct *next; ; struct database_struct { struct list_item_struct *first; ; typedef struct list_item_struct list_item; typedef struct database_struct database; int initialize_db( database *db ) { db->first = NULL; 13

Adding list elements int add_to_db( database *db, char *name, char *address ) { list_item *new_item_ptr; new_item_ptr = (list_item *) malloc(sizeof(list_item)); if( new_item_ptr == NULL ) return -1; if( strlen(name) >= NAME_SIZE strlen(address) >= ADD_SIZE ) return -1; strcpy( new_item_ptr->name, name ); strcpy( new_item_ptr->address, address ); new_item_ptr->next = db->first; db->first = new_item_ptr; return 0; 14

Putting it together void print_item( list_item l ) { printf( "Name: %s\n", l.name ); printf( "Address: %s\n\n", l.address ); void print_db( database db ) { list_item *l = db.first; while( l!= NULL ) { print_item( *l ); l = l->next; void main() { database db; initialize_db( &db ); add_to_db( &db, "Erik Sherwood", "1234 Street Ave." ); add_to_db( &db, "Homer Simpson", "742 Evergreen Terrace" ); add_to_db( &db, "Tony Blair", "10 Downing Street" ); print_db( db ); 15

Removing elements void remove_from_db( database *db, list_item *item ) { list_item *l = db->first; /* if database is empty */ if( l == NULL ) return; /* if first element is the item */ if( l == item ) { db->first = l->next; free( l ); l = NULL; return; /* otherwise, try to find it */ while( l->next!= NULL && l->next!= item ) l = l->next; /* we ve either found item, or come to the end of the list */ if( l->next == item ) { /* skip item in the list, and free memory */ l->next = item->next; free( item ); item = NULL; 16