Dynamic Data Structures. CSCI 112: Programming in C

Similar documents
Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

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

CS 11 C track: lecture 5

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

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

Lecture 8 Dynamic Memory Allocation

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) {

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

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

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

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

CSC 1600 Memory Layout for Unix Processes"

Class Information ANNOUCEMENTS

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

Dynamic memory allocation (malloc)

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

Heap Arrays. Steven R. Bagley

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

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

CS 222: Pointers and Manual Memory Management

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

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

Dynamic Memory: Alignment and Fragmentation

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

C PROGRAMMING Lecture 5. 1st semester

Contents of Lecture 3

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

Cpt S 122 Data Structures. Data Structures

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

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

Dynamic Memory Allocation

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

Fall 2018 Discussion 2: September 3, 2018

Fundamentals of Programming

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

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Memory Management. CSC215 Lecture

CSCI 171 Chapter Outlines

CS61C : Machine Structures

C Structures & Dynamic Memory Management

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

dynamic memory allocation

Heap Arrays and Linked Lists. Steven R. Bagley

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

Memory Allocation. General Questions

LOÏC CAPPANERA. 1. Memory management The variables involved in a C program can be stored either statically or dynamically.

DAY 3. CS3600, Northeastern University. Alan Mislove

Pointers. Introduction

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

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

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

Dynamic Allocation in C

CS61, Fall 2012 Section 2 Notes

Memory management. Johan Montelius KTH

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

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

High Performance Programming Programming in C part 1

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

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

CS24 Week 2 Lecture 1

C Programming Basics II

(1-2) Introduction to C Data Structures & Abstract Data Types. Instructor - Andrew S. O Fallon CptS 122 (June 6, 2018) Washington State University

Lecture Notes on Memory Management

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Understanding Pointers

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

Arrays, Pointers and Memory Management

Arrays and Memory Management

Quick review pointer basics (KR ch )

Pointers and Terminal Control

Section 2: Processes

Structures and Pointers

Dynamic memory allocation

CS61C : Machine Structures

Intermediate Programming, Spring 2017*

Unit IV & V Previous Papers 1 mark Answers

Dynamic Allocation in C

Memory (Stack and Heap)

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

4) In C, if you pass an array as an argument to a function, what actually gets passed?

Dynamic Memory Allocation and Command-line Arguments

Kurt Schmidt. October 30, 2018

Lecture Notes on Memory Management

CS61C : Machine Structures

Dynamic Memory Allocation

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

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Interlude: Memory API

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

Programs in memory. The layout of memory is roughly:

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

CS201 Some Important Definitions

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Low-Level C Programming. Memory map Pointers Arrays Structures

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Arrays and Pointers (part 1)

Transcription:

Dynamic Data Structures CSCI 112: Programming in C 1

It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable or array. These variables are only alive during the specific block of code in which they were created This isn t always efficient or flexible: what if we don t know the size of a list at compile time? What if we want more control of when a variable is created and deleted? Enter dynamic memory allocation, a C feature which gives us explicit control over memory management. 2 2

What are the drawbacks of letting the compiler do the allocation? int main(void) { char arr[400]; } void my_function() { int x;... } 3 3

What are the drawbacks of letting the compiler do the allocation? int main(void) { char arr[400]; } void my_function() { int x;... } arr will take up exactly 400 bytes, no matter how many elements we use. What if we need more than 400? What if we only actually use 300? x is no longer alive after my_function eds. 4 4

Dynamic Memory Allocation in a nutshell Dynamic memory allocation lets us obtain more memory when we need it, and to release memory back to the system when we don t need it. It lets us do this while the program is running we can base memory needs off of user input, for example. 5 5

First things first: the heap and the stack The stack is where C allocates memory for variables it creates automatically, within functions. (This is what we ve done up until now.) When a function is called, the local variables for that function are allocated on the top of the stack, so the the function can read and write to them. When the function terminates, those variables are deallocated. (Erased. from the stack.) 6 6

First things first: the heap and the stack The heap is a more stable part of memory. Variables that are created here remain in existence for the duration of the program. Variables are not tied to a specific function like those in the stack are. This is where dynamically allocated variables are stored. 7 7

Make sure to include stdlib.h in order to use the following memory management functions! 8 8

Allocating space for a variable: malloc malloc allocates a specified amount of space on the heap, and returns a pointer to where that space starts. It takes one argument: an integer representing how many bytes to allocate. Let s say we want to allocate space for an int: malloc( sizeof(int) ) The above call gives us back a void pointer (address) to the allocated block of memory. The sizeof function gives us exactly how many bytes we need for a given type. 9 9

Allocating space for a variable: malloc We can cast this void pointer to a specific pointer type, allowing us to use the newly allocated space in our code: // Create some pointers char *letp; int *nump; // Dynamically allocate memory blocks // Assign the above pointers to point to those blocks // We need to cast the void pointer returned by malloc // to the right type of pointer. letp = (char*) malloc( sizeof(char) ); nump = (int*) malloc( sizeof(int) ); 10 10

Allocating space for a variable: malloc Here s how this code affects memory: (Notice that the pointers are on the stack, since they were created in a function. Dynamically allocated blocks are on the heap.) Stack 11 11

Allocating space for a struct: malloc It s just as easy to dynamically allocate memory for a struct: typedef struct planet { int radius; char name[5];... } planet_t; planet_t *p = (planet_t*) malloc( sizeof(planet_t) ); 12 12

Allocating space for a struct: malloc Once again, here s what that looks like in memory. Notice that malloc creates enough space for all components of the planet structure. Stack Heap 13 13

Allocating space for an array: calloc malloc allocates a single block of memory for a built-in or user defined type (such as a struct). We can use calloc (contiguous allocation) to allocate an array of blocks. It takes two arguments number of elements and size of each element. Besides allocating space, it also initializes each element to 0. This is the main difference between malloc and calloc. While malloc could allocate the same amount of space as a call to calloc, it would not initialize array elements to 0. 14 14

Allocating space for an array: calloc In code: int number_of_elements = 4; int *int_array = (int*) calloc(number_of_elements, sizeof(int)); In memory: Stack Heap *int_array 0 0 0 0 15 15

Returning cells to the heap: free free let us deallocate a cell, or indicate that we no longer need it. The cell can then be allocated for another variable. It s what the Garbage Collector does automatically in Java. To free a block of memory associated with a pointer x, just do this: free(x) 16 16

Returning cells to the heap: free In this code,, we dynamically allocate space for a double, assign it a value, make a copy of it, then free that space. The cell containing 49.5 may be reallocated after the call to free. So we can t use it anymore. Even though xp and xcopyp still exist as pointers, they cannot be used to reference the cell. 17 17