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

Similar documents
Cpt S 122 Data Structures. Data Structures

Memory Management. CSC215 Lecture

Dynamic Data Structures. CSCI 112: Programming in C

Lecture 8 Dynamic Memory Allocation

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

Memory (Stack and Heap)

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

C Structures & Dynamic Memory Management

Programs in memory. The layout of memory is roughly:

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:

CS 11 C track: lecture 5

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

Dynamically Allocated Memory in C

Memory Allocation. General Questions

Dynamic Allocation of Memory

Dynamic Memory Allocation

Dynamic memory allocation

Heap Arrays. Steven R. Bagley

Dynamic Memory Allocation

Understanding Pointers

Example: Runtime Memory Allocation: Example: Dynamical Memory Allocation: Some Comments: Allocate and free dynamic memory

CS24 Week 2 Lecture 1

Dynamic Memory Allocation: Basic Concepts

2/9/18. Secure Coding. CYSE 411/AIT681 Secure Software Engineering. Agenda. Dynamic Memory Interface. Dynamic Memory Interface

Memory Management. CS449 Fall 2017

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

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

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

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

Linked data structures. EECS 211 Winter 2019

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

Dynamic memory allocation (malloc)

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

Dynamic Memory Allocation: Basic Concepts

CP2 Revision. theme: dynamic datatypes & data structures

Computer Programming Practice (2008 Winter) Practice 10 C Scoping & Pointer

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package

Programming in C. Lecture 5: Aliasing, Graphs, and Deallocation. Dr Neel Krishnaswami. Michaelmas Term University of Cambridge

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

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Dynamic memory. EECS 211 Winter 2019

Kurt Schmidt. October 30, 2018

Solution for Data Structure

Advanced Pointer Topics

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

Linked Lists. .. and other linked structures. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

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

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package

Dynamic Data Structures (II)

14. Memory API. Operating System: Three Easy Pieces

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

Structures and Pointers

A First Book of ANSI C

Memory Organization. The machine code and data associated with it are in the code segment

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

Introduction to Data Structures. Systems Programming

Data Structure Series

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation

POINTER AND ARRAY SUNU WIBIRAMA

CSCI 171 Chapter Outlines

Heap Arrays and Linked Lists. Steven R. Bagley

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

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

BBM 201 DATA STRUCTURES

Arrays and Memory Management

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Reminder: compiling & linking

Secure Software Programming and Vulnerability Analysis

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

Computer Systems and Networks

dynamic memory allocation

Midterm Review. CS 211 Fall 2018

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations

CSC 1600 Memory Layout for Unix Processes"

CS61, Fall 2012 Section 2 Notes

Systems Programming and Computer Architecture ( )

Introduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th

MODULE 5: Pointers, Preprocessor Directives and Data Structures

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

Implementing an abstract datatype. Linked lists and queues

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

Programming. Lists, Stacks, Queues

CS349/SE382 A1 C Programming Tutorial

Programming in C. Lecture Tiina Niklander. Faculty of Science

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

Chapter 19 Data Structures -struct -dynamic memory allocation

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

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

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

malloc(), calloc(), realloc(), and free()

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

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

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Binghamton University. CS-211 Fall Dynamic Memory

Dynamic Memory Allocation. Gerson Robboy Portland State University. class20.ppt

Transcription:

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

Dynamic Memory Allocation Dynamic memory allocation is used to obtain and release memory during program execution. Up until this point we reserved memory at compile time using declarations. You have to be careful with dynamic memory allocation. It operates at a low-level, you will often find yourself having to do a certain amount of work to manage the memory it gives you. To use the functions discussed here, you must include the stdlib.h header file. Four Dynamic Memory Allocation Functions: Allocate memory - malloc(), calloc(), and realloc() Free memory - free()

malloc() To allocate memory use void *malloc(size_t size); Takes number of bytes to allocate as argument. Use sizeof to determine the size of a type. Returns pointer of type void *. A void pointer may be assigned to any pointer. If no memory available, returns NULL. e.g. char *line; int linelength = 100; line = (char*)malloc(linelength);

Allocating memory for a struct You can also allocate memory for a struct. Example: struct node *newptr; newptr = (struct node *)malloc(sizeof(struct node)); Memory allocated with malloc() lasts as long as you want it to. It does not automatically disappear when a function returns, as automatic-duration variables do, but it does not have to remain for the entire duration of your program, either. There is a mechanism to free allocated memory.

free() To release allocated memory use void free(void *p) Deallocates memory allocated by malloc(). Takes a pointer as an argument. e.g. free(newptr); Freeing unused memory is a good idea, but it's not mandatory. When your program exits, any memory which it has allocated but not freed will be automatically released.

malloc Example #include <stdio.h> #include <stdlib.h> void main () { int i, *p; /* Allocate a block of n ints */ p = (int *) malloc(n * sizeof(int)); if (p == NULL) { perror("malloc"); exit(0); } /* Initialize allocated block */ for (i=0; i<n; i++) p[i] = i; } /* Return allocated block to the heap */ free(p);

malloc Example x: a one-dimensional, 10-element array of integers int *x; //int x[10] or #define SIZE 10 int x[size]; x = (int *) malloc(10 * sizeof(int)); If the declaration is to include the assignment of initial values, however, then x must be defined as an array rather than a pointer variable. int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 7

calloc() Similar to malloc(), the main difference is that the values stored in the allocated memory space are zero by default. With malloc(), the allocated memory could have any value. calloc() requires two arguments - the number of variables you'd like to allocate memory for and the size of each variable. void *calloc(size_t nitem, size_t size); Like malloc(), calloc() will return a void pointer if the memory allocation was successful, else it'll return a NULL pointer.

realloc() If you find you did not allocate enough space use realloc(). You give realloc() a pointer (such as you received from an initial call to malloc()) and a new size, and realloc does what it can to give you a block of memory big enough to hold the new size. int *ip; ip = (int*)malloc(100 * sizeof(int));... /* need twice as much space */ ip = (int*)realloc(ip, 200 * sizeof(int));

Geo/Geo/1 Simulations Queue dynamics qq kk + 1 = max{qq kk + aa kk ss kk, 0} typedef structure DNode { double atime; // file arrival time int fsize; // file size } File;

Doubly Linked List A doubly linked list provides a natural implementation of the List ADT Nodes implement Position and store: element link to the previous node link to the next node Special trailer and header nodes prev elem next node header nodes/positions trailer elements 11

Sentinel Nodes To simplify programming, two special nodes have been added at both ends of the doubly-linked list. Header and trailer are dummy nodes, also called sentinels, do not store any data elements. Header: header sentinel has a null-prev reference (link). Trailer: trailer sentinel has a null-next reference (link). 12

What we see from a Douby-linked List? A doubly-linked list object would need to store the following: 1. Reference to sentinel header-node; 2. Reference to sentinel trailer-node; and 3. Size-counter that keeps track of the number of nodes in the list (excluding the two sentinels). 13

Empty Doubly-Linked List: Using sentinels, we have no nulllinks; instead, we have: header.next = tail trailer.prev = header Single Node List: Size = 1 This single node is the first node, and also is the last node: first node is header.next last node is trailer.prev header header first trailer last trailer 14

Examples typedef structure DNode { double atime; // file arrival time int fsize; // file size Dnode* prev; //previous node in list Dnode* next; // next node in list } File; typedef structure { File * header; File * trailer; } Queue; //first node in list // last node in list

Operations of Doubly-Linked List IsEmpty: determine whether or not the list is empty AddFile: insert a new node at a particular position Remove: find a node with a given value

IsEmpty() int IsEmpty() { } return (header->next == trailer);

Queue* AddFile(Queue* myqueue, double time, int size) Queue* AddFile(Queue* myqueue, double time, int size) { File* u = (File*)malloc(sizeof(File)); // create a new node u->atime = time; u->fsize = size; File* Lastfile = (File*)malloc(sizeof(File)); Lastfile = myqueue->trailer; u->next = Lastfile; u->prev = Lastfile->prev; trailer w } Lastfile->prev->next = u; Lastfile->prev = u; return myqueue;

Queue* AddFile(Queue* myqueue, double time, int size) Queue* AddFile(Queue* myqueue, double time, int size) { File* u = (File*)malloc(sizeof(File)); // create a new node u->atime = time; u->fsize = size; File* Lastfile = (File*)malloc(sizeof(File)); Lastfile = myqueue->trailer; u->next = Lastfile; u->prev = Lastfile->prev; trailer w Lastfile->prev->next = u; Lastfile->prev = u; u } return myqueue;

Queue* Remove(Queue* myqueue, File* f) Queue* Remove(Queue* myqueue, File* f) { File* u = (File*)malloc(sizeof(File)); File* v = (File*)malloc(sizeof(File)); u = f->prev; v = f->next; // remove Node f } u->next = f->next; v->prev = f->prev; free(f); return myqueue; v f u

Queue* Remove(Queue* myqueue, File* f) Queue* Remove(Queue* myqueue, File* f) { File* u = (File*)malloc(sizeof(File)); File* v = (File*)malloc(sizeof(File)); u = f->prev; v = f->next; // remove Node f } u->next = f->next; v->prev = f->prev; free(f); return myqueue; v u

Queue* RemoveFront(Queue* myqueue) Queue* RemoveFront(Queue* myqueue) { // remove the firstnode myqueue = Remove(myQueue, myqueue->header->next); return myqueue; } w u header

Queue* RemoveFront(Queue* myqueue) Queue* RemoveFront(Queue* myqueue) { // remove the firstnode myqueue = Remove(myQueue, myqueue->header->next); return myqueue; } w header