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

Kurt Schmidt. October 30, 2018

CS24 Week 2 Lecture 1

CS349/SE382 A1 C Programming Tutorial

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

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

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

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

ECE 15B COMPUTER ORGANIZATION

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

CS61C Midterm Review on C & Memory Management

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

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

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

CS 11 C track: lecture 5

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

CS 241 Data Organization Binary Trees

CS61, Fall 2012 Section 2 Notes

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

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

CSC231 C Tutorial Fall 2018 Introduction to C

Heap Arrays and Linked Lists. Steven R. Bagley

Lecture 04 Introduction to pointers

Programs in memory. The layout of memory is roughly:

Heap Arrays. Steven R. Bagley

BBM 201 DATA STRUCTURES

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

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

Arrays and Pointers (part 1)

Lecture 3: C Programm

Writing Functions in C

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

However, in C we can group related variables together into something called a struct.

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

Lectures 13 & 14. memory management

POINTER AND ARRAY SUNU WIBIRAMA

CS C Primer. Tyler Szepesi. January 16, 2013

Lecture 8 Dynamic Memory Allocation

CS113: Lecture 4. Topics: Functions. Function Activation Records

Functions in C C Programming and Software Tools

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

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

C Structures & Dynamic Memory Management

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

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Class Information ANNOUCEMENTS

DAY 3. CS3600, Northeastern University. Alan Mislove

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

CS61C : Machine Structures

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

CSC C69: OPERATING SYSTEMS

EL2310 Scientific Programming

CS 222: Pointers and Manual Memory Management

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 19 November 2014

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

Dynamic memory. EECS 211 Winter 2019

Week 7 Part I. Kyle Dewey. Monday, August 6, 12

Lectures 5-6: Introduction to C

Dynamic Memory Management

Arrays and Memory Management

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

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

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

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

Arrays and Pointers (part 1)

Intermediate Programming, Spring 2017*

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

Common Misunderstandings from Exam 1 Material

Pointers II. Class 31

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

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

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

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

C Programming Basics II

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Memory Management. CS31 Pascal Van Hentenryck CS031. Lecture 19 1

Pointers, Dynamic Data, and Reference Types

Fall 2018 Discussion 2: September 3, 2018

a data type is Types

Lecture 2: C Programm

G52CPP C++ Programming Lecture 10. Dr Jason Atkin

Section Notes - Week 1 (9/17)

Data Representation and Storage. Some definitions (in C)

CS61C : Machine Structures

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

CS61 Section Notes. Section 5 (Fall 2011) Topics to be covered Common Memory Errors Dynamic Memory Allocation Assignment 3: Malloc

Chapter 1 Getting Started

Understanding Pointers

Dynamic Memory Allocation

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Singly linked lists in C.

CS61C : Machine Structures

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

Memory Management in C (Dynamic Strings) Personal Software Engineering

ECE 2400 Computer Systems Programming Fall 2018 Topic 6: C Dynamic Allocation

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; 8

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. 9

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" ); 10

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; 11

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; 12

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, "Kevin O Neill", "1234 Street Ave." ); add_to_db( &db, "Homer Simpson", "742 Evergreen Terrace" ); add_to_db( &db, "Tony Blair", "10 Downing Street" ); print_db( db ); 13

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 ); 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 ); 14