Binghamton University. CS-211 Fall Dynamic Memory

Similar documents
Dynamic Data Structures. CSCI 112: Programming in C

CS 11 C track: lecture 5

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

Heap Arrays. Steven R. Bagley

TI2725-C, C programming lab, course

C PROGRAMMING Lecture 5. 1st semester

CS 241 Data Organization Binary Trees

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

Programs in memory. The layout of memory is roughly:

Memory Allocation. General Questions

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

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

Pointers review. int a = 5; int *ptr = &a; cout << *ptr;

DAY 3. CS3600, Northeastern University. Alan Mislove

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

Lecture 8 Dynamic Memory Allocation

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

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

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

Kurt Schmidt. October 30, 2018

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

Welcome! COMP s1. Programming Fundamentals

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

Heap Arrays and Linked Lists. Steven R. Bagley

Dynamic Memory Allocation

My malloc: mylloc and mhysa. Johan Montelius HT2016

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

CS61C Midterm Review on C & Memory Management

Dynamic Allocation of Memory

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

Dynamic Allocation in C

CS24 Week 2 Lecture 1

Writing Functions in C

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

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

Memory (Stack and Heap)

Memory Management. CSC215 Lecture

Dynamic Allocation in C

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

14. Memory API. Operating System: Three Easy Pieces

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

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

CSC 1600 Memory Layout for Unix Processes"

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

CS61, Fall 2012 Section 2 Notes

CA341 - Comparative Programming Languages

Dynamic Memory Management

Singly linked lists in C.

Memory Management. CS449 Fall 2017

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

CS 222: Pointers and Manual Memory Management

C Programming Basics II

CS61C : Machine Structures

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING

Dynamic Memory Management! Goals of this Lecture!

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

Dynamic Memory Management

CS 322 Operating Systems Programming Assignment 4 Writing a memory manager Due: April 5, 11:30 PM

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

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

Dynamic memory. EECS 211 Winter 2019

CMSC 341 Lecture 2 Dynamic Memory and Pointers

CS61C : Machine Structures

CS61C : Machine Structures

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CS201 Some Important Definitions

Class Information ANNOUCEMENTS

C Structures & Dynamic Memory Management

Common Misunderstandings from Exam 1 Material

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

CS61C : Machine Structures

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Arrays and Memory Management

Computer Programming Unit 3

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

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

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

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

Dynamic Memory Allocation: Advanced Concepts

Intermediate Programming, Spring 2017*

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

Secure Coding in C and C++

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

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

Recitation: C Review. TA s 20 Feb 2017

CS 322 Operating Systems Practice Midterm Questions

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

Hacking in C. Memory layout. Radboud University, Nijmegen, The Netherlands. Spring 2018

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Memory Management in C (Dynamic Strings) Personal Software Engineering

A First Book of ANSI C

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

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

Dynamic Memory Allocation

COSC Software Engineering. Lecture 16: Managing Memory Managers

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

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

Dynamic Memory & ADTs in C. The heap. Readings: CP:AMA 17.1, 17.2, 17.3, The primary goal of this section is to be able to use dynamic memory.

Transcription:

Dynamic Memory

Static Memory Define variables when we write code When we write the code we decide What the type of the variable is How big array sizes will be etc. These cannot change when we run the code! For example: char buffer[100]= This is a test. ; 2

Implications of Static Memory Imposes limits on what our programs can handle readline(&buffer[0]) can t handle a line that s more than 99 chars long! Forces us to allocate enough space for the worst case Waste space for the average case! char buffer[4096]; // More than enough for one line 3

Dynamic Memory Standard library function call to request new memory #include <stdlib.h> void * malloc(int size); Number of Bytes requested Address of space returned NULL if no space is available Type is pointer to nothing. 4

What does malloc mean? (Abbreviation for memory allocation ) Operating system owns a portion of the address spaced called the HEAP a heap of memory When you invoke malloc, the operating system finds a portion of the heap large enough to hold the number of bytes you requested By returning the address of that memory to you, the Operating System is granting control of that memory to you! Operating system is guaranteeing that no one other than your program will use that memory! 5

What s in malloc ed memory? malloc does not initialize memory for you! You get whatever is in memory when malloc completes Alternative: calloc void *calloc(int num,int size); Allocs num contiguous elements of size bytes each Initializes everything to zero 6

The malloc contract You are guaranteed sole use of malloc ed memory Nothing outside of your program will read or write that memory When you are finished using that memory, you must give it back to the operating system! char * buffer=(char *)malloc(300); // get 300 bytes from heap // use buffer here free(buffer); // return buffer 300 bytes to the heap 7

Graphic View of Heap char * x=malloc(1200); char * y=malloc(900); free(y); free(x); 8

Dynamic Node Allocation/Free struct node { int value; char * next; }; struct node * makenode(int value) { struct node * np= (struct node *)malloc(sizeof(struct node)); np->value=value; np->next=null; return np; } void freenode(struct node * np) { free(np); } 9

The C sizeof operator/function Argument can be: Type Variable (or expression) Returns : number of bytes required for that type or for a variable in bytes sizeof(char)==1, sizeof(int)==4, sizeof(num[4])==16 sizeof(struct node)==8 (int value; struct node *next) 10

Why Dynamic Get exactly as much memory as you need No program limits No wasted space Get memory as many times as you need e.g. memory for each node in a list Don t have to guess how many nodes you will need Don t care how many nodes you need! 11

strdup char * strdup(char * from); Combination of malloc and strcpy char * strdup(char *from) { char *to= malloc(strlen(from)+1); strcpy(from,to); return to; } Need to free result! char buffer[4096]; while (!feof(stdin)) { buffer=getline(); char *ln=strdup(buffer); } for( ) free(ln); } 12

Why is free important? As long as you own memory, no-one else can use it If you don t free, eventually, nothing is left in the heap malloc then returns NULL pointers small print when your program exits, any space you have malloc ed is freed. It s not uncommon to run for days and days Do you turn off your laptop? Many programs start when you turn on your laptop, and don t stop until you turn off your laptop. Be a good citizen free your malloc ed memory 13

Problem: Dangling Pointers char *buffer=(char *)malloc(300); // get 300 bytes strcpy(buffer, This is a test ); // use it free(buffer); strcpy(buffer, This was a test ); returns space to heap does not change the value of buffer! writes to memory I no longer own! May work, but cause other problems May cause segmentation violation 14

VALGRIND Memory Leak: Memory that has been malloc ed, but not free d Special program: valgrind monitors each malloc monitors each free Reports on mallocs that have no corresponding free when program exits run as: valgrind --leak-check=full./program arg1 arg2 <input.txt Also reports on references to free d memory Also reports on array bounds violations (Not available on Cygwin) 15

Alternative: Garbage Collection Need to know when programmer is using memory Use of pointers introduce aliases Therefore, pointers and garbage collection don t go together Periodically stop program execution for garbage collection Automatically free any memory that the program is no longer using. Requires significant analysis to ensure you don t throw away something useful Adds about 10% performance penalty Benefit: Allows programmers to be sloppy housekeepers 16

Example of malloc and free tokenizeverilog.c (Project 2) malloc is invoked to provide space for identifiers No need to free because we are only working with one file tokenizeverilog (Project 3) malloc is invoked to provide space for identifiers Need to free space because we don t know how many files we will need Need to keep a linked list of malloc ed memory

Memory List Handle struct vhandle mlist NULL

Memory List first new token Handle struct vhandle mlist struct mlist next mem NULL token

Memory List next new token Handle struct vhandle mlist struct mlist next mem struct mlist next mem token

Memory List Free Handle struct vhandle mptr mlist struct mlist next mem struct mlist next mem

Memory List Free Handle struct vhandle mptr mlist struct mlist next mem struct mlist next mem

Memory List Free Handle struct vhandle tptr mptr mlist struct mlist next mem struct mlist next mem

Memory List Free Handle struct vhandle mptr mlist struct mlist next mem

Resources Programming in C, Chapter 16 (Dynamic Memory Allocation) Wikipedia Memory Management https://en.wikipedia.org/wiki/memory_management valgrind home http://valgrind.org/ Dynamic Memory Allocation Tutorial http://randu.org/tutorials/c/dynamic.php 25