Memory Management. CS449 Fall 2017

Size: px
Start display at page:

Download "Memory Management. CS449 Fall 2017"

Transcription

1 Memory Management CS449 Fall 2017

2 Life9mes Life9me: 9me from which a par9cular memory loca9on is allocated un9l it is deallocated Three types of life9mes Automa9c (within a scope) Sta9c (dura9on of program) Manual (explicitly controlled by programmer) Manual control involves inser9ng into your code Alloca9on calls Dealloca9on calls

3 Manual Alloca9on Pros/Cons Pros (Flexibility) Can create storage loca9ons on demand without declaring them as variables Useful for construc9ng dynamic data structures (e.g. linked lists, trees, graphs) whose size and shape can change depending on user input Cons (Complexity) Programmer has to think about the behavior of program to determine the life9mes of loca9ons

4 C Standard Library Memory Management Func9ons Just #include <stdlib.h> Declara9ons for malloc(), calloc(), free(), realloc() Func9ons to request alloca9on/dealloca9on C Standard Library takes care of the nivygrivy details of memory management System calls to request memory from OS Keeping track of areas of allocated memory Keeping track of areas of free memory Searching for suitable area to allocate memory

5 Alloca9on Func9ons void *malloc(size_t size) Allocates size bytes and returns a pointer to the allocated memory (NULL on failure) Memory is not cleared void *calloc(size_t nmemb, size_t size) Allocates nmemb * size bytes and returns a pointer to the allocated memory (NULL on failure) Memory is set to 0 Check return value for out-of-memory error

6 Dealloca9on Func9on void free(void *ptr) Frees the memory space pointed to by ptr, which must have been previously allocated Counterpart for both malloc() and calloc() If free() has already been called on the same loca9on, behavior is undefined

7 Re-Alloca9on Func9on void *realloc(void *ptr, size_t size) Changes size of memory pointed to by ptr to size bytes Returns pointer to resized memory (NULL on failure) May be different from ptr, if C library decides to move data to a more suitable sized block of memory May be same as ptr, if no need to move data (e.g. for contrac9on) If expanded, expanded memory will be unini9alized If ptr is NULL, same as malloc(size) If size is zero, and ptr is not NULL, same as free(ptr) Use when you want to resize previously allocated memory without losing its contents

8 Malloc/Free Example #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { } int *p, i, length = atoi(argv[1]); p = (int *)malloc(length * sizeof(int)); srand((unsigned int)9me(null)); for(i = 0; i < length; i++) p[i] = rand(); for(i = 0; i < length; i++) pring("%d \n", p[i]); free(p); return 0; >>./a.out

9 Malloc/Free Example #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { } int *p, i, length = atoi(argv[1]); p = (int *)malloc(length * sizeof(int)); srand((unsigned int)9me(null)); for(i = 0; i < length; i++) p[i] = rand(); for(i = 0; i < length; i++) pring("%d \n", p[i]); free(p); return 0; malloc(): Calculate the number of bytes of memory you want to allocate using sizeof free(): Free memory no longer needed The life9me of the loca9ons allocated using malloc() is independent of pointer p Pointer p: scope of main() Allocated loca9on: between malloc() and free() What if you never free()? Memory stays around un9l end of program execu9on

10 Malloc ed Memory Lives in Heap 0xc Stack (Automatic variables) Unused memory space brk (program break) 0 Heap (Malloc ed Memory) Data Segment (Static variables) Text Segment ( Function Code) Heap starts at 0 bytes on program launch Heap grows / shrinks as program allocates / deallocates memory

11 How Malloc() Manages the Heap Malloc() / free() do not manage heap directly Built on top of 3 system calls: brk(), mmap(), munmap() Why must C library rely on system calls? Memory is a hardware resource managed by OS Must go through OS to change program memory usage int brk(void *addr) Changes program break (top of heap) to addr Increasing program break è allocates memory Decreasing program break è deallocates memory mmap() and munmap() Alterna9ve way to allocate / deallocate memory on demand Try doing man mmap or man munmap on thoth

12 Tracing System Calls for malloc #include <stdlib.h> int main(int argc, char *argv[]) { } void *mem[100]; int i = 0; for(i = 0; i < 100; i++) { mem[i] = malloc(4096); } for(i = 0; i < 100; i++) { } free(mem[i]); return 0; >> strace./a.out [sic] brk(0) brk(0x623000) brk(0x644000) brk(0x665000) brk(0x686000) brk(0x622000) [sic] = 0x = 0x = 0x = 0x = 0x = 0x Top of heap increases gradually, peaks at 0x Not as many brk calls as malloc calls Why? C lib Increases heap in large chunks to minimize number of system calls Top of heap decreases dras9cally to 0x When last memory chunk at top of heap is freed

13 Common Memory Errors Memory Leak Cause: Forgewng to free unused memory Effect: Steady rise in memory consump9on un9l out-of-memory error Dangling Pointer Cause: Accessing memory that has already been freed Effect: Corrup9on when that memory used for something else Double Free Cause: Freeing the same memory loca9on twice Effect: Undefined. Depends on C stdlib implementa9on. Out-of-bounds Access Cause: Accessing memory beyond the alloca9on boundary Effect: Corrup9on if memory beyond boundary used for something else Memory errors are typically Heisenbugs (non-determinis9c bugs)

14 Memory Management C vs. Java Why does Java not have memory errors? Memory leak, double free, dangling pointer: no frees Out-of-bounds access: run9me bounds checks by JVM Why is free() required in C but not Java? Most applica9on-centric languages (e.g. Java, Python, JavaScript) have automa9c garbage collec9on See garbage collec9on slide C opted for manual freeing To reduce execu9on 9me overhead due to GC To reduce memory overhead due to garbage Flip side: must be very careful to avoid memory errors

15 Memory Management Strategy Basic rules for alloca9on Malloc() before using memory (just like new in Java) Basic rules for dealloca9on Free() when memory can no longer be reached by program That is, exactly when the last pointer referencing it is lost Freeing before: can lead to dangling pointer Freeing a{er: last pointer is gone, so no way to free! Memory leak! This is actually the rule used by the Java garbage collector How do you know if you are the last pointer? Some9mes easily deducible from code Some9mes must use reference counter (how many point to you)

16 Valgrind Diagnos9c tool that detects run9me errors (memory management errors among them) Command: valgrind [op9ons] <program> Not perfect Can miss errors (some9mes) Since test cases cannot cover all possible execu9on paths Can report errors when there are none (rarely) Due to weaknesses in detec9on algorithm Slows down program execu9on significantly Keep memory errors from creeping in using a good memory management strategy Use valgrind as a last resort

17 Valgrind Memory Leak Example #include <stdio.h> #include <stdlib.h> int main () { } char *p = malloc(100); return 0; >> gcc g main.c >>./a.out >> valgrind --leak-check=full --track-origins=yes./a.out ==32563== HEAP SUMMARY: ==32563== in use at exit: 100 bytes in 1 blocks ==32563== total heap usage: 1 allocs, 0 frees, 100 bytes allocated ==32563== ==32563== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==32563== at 0x4A069EE: malloc (vg_replace_malloc.c:270) ==32563== by 0x4004DC: main (main.c:5) The -g op9on given to GCC inserts debug symbols to binary, enabling valgrind to locate the errors more accurately Shows 100 bytes of memory malloc ed in main.c:5 is lost

18 Valgrind Double Free Example #include <stdio.h> >> gcc g main.c #include <stdlib.h> >>./a.out int main () >> valgrind --leak-check=full --track-origins=yes./a.out { ==4686== Invalid free() / delete / delete[] / realloc() char *p = malloc(100); ==4686== at 0x4A063F0: free (vg_replace_malloc.c:446) free(p); ==4686== by 0x400531: main (main.c:7) free(p); ==4686== Address 0x4c37040 is 0 bytes inside a block of size 100 free'd return 0; ==4686== at 0x4A063F0: free (vg_replace_malloc.c:446) } ==4686== by 0x400525: main (main.c:6) Shows memory free d in main.c:7 has already been free d previously in main.c:6

19 Valgrind Dangling Pointer Example #include <stdio.h> >> gcc g main.c #include <stdlib.h> >>./a.out int main () >> valgrind --leak-check=full --track-origins=yes./a.out { ==4814== Invalid write of size 1 char *p = malloc(100); ==4814== at 0x40052A: main (main.c:7) free(p); ==4814== Address 0x4c37040 is 0 bytes inside a block of size 100 free'd p[0] = H ; ==4814== at 0x4A063F0: free (vg_replace_malloc.c:446) return 0; ==4814== by 0x400525: main (main.c:6) } Shows invalid write to memory of size 1 in main.c:7, where the memory has already been free d previously in main.c:6

20 Valgrind Out-of-bounds Example #include <stdio.h> >> gcc g main.c #include <stdlib.h> >>./a.out int main () >> valgrind --leak-check=full --track-origins=yes./a.out { ==4950== Invalid write of size 1 char *p = malloc(100); ==4950== at 0x400522: main (main.c:6) p[100] = H ; ==4950== Address 0x4c370a4 is 0 bytes a{er a block of size 100 alloc'd free(p); ==4950== at 0x4A069EE: malloc (vg_replace_malloc.c:270) return 0; ==4950== by 0x400515: main (main.c:5) } Shows invalid write to memory of size 1 in main.c:6, where the memory is a{er a block of memory previously alloc ed in main.c:5

Memory (Stack and Heap)

Memory (Stack and Heap) Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03

More information

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

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly

More information

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

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

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

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

Dynamic Memory Alloca/on: Basic Concepts

Dynamic Memory Alloca/on: Basic Concepts Dynamic Memory Alloca/on: Basic Concepts 15-213 / 18-213: Introduc2on to Computer Systems 18 th Lecture, March. 26, 2013 Instructors: Anthony Rowe, Seth Goldstein, and Gregory Kesden 1 Today Basic concepts

More information

Debugging (Part 2) 1

Debugging (Part 2) 1 Debugging (Part 2) 1 Programming in the Large Steps Design & Implement Program & programming style (done) Common data structures and algorithms Modularity Building techniques & tools (done) Test Testing

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

Princeton University. Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management

Princeton University. Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management Princeton University Computer Science 217: Introduction to Programming Systems Dynamic Memory Management 1 Agenda The need for DMM DMM using the heap section DMMgr 1: Minimal implementation DMMgr 2: Pad

More information

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic Memory Allocation (and Multi-Dimensional Arrays) Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan

More information

Princeton University Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management

Princeton University Computer Science 217: Introduction to Programming Systems. Dynamic Memory Management Princeton University Computer Science 217: Introduction to Programming Systems Dynamic Memory Management 1 Goals of this Lecture Help you learn about: The need for dynamic* memory mgmt (DMM) Implementing

More information

Dynamic Memory Alloca/on: Basic Concepts

Dynamic Memory Alloca/on: Basic Concepts Dynamic Memory Alloca/on: Basic Concepts Fall 2015 Instructor: James Griffioen Adapted from slides by R. Bryant and D. O Hallaron (hip://csapp.cs.cmu.edu/public/instructors.html) 1 Today Basic concepts

More information

COSC Software Engineering. Lecture 16: Managing Memory Managers

COSC Software Engineering. Lecture 16: Managing Memory Managers COSC345 2013 Software Engineering Lecture 16: Managing Memory Managers Outline Typical problems (from previous lectures) Memory leaks aren t just for (Objective) C Tracking malloc() calls Catching calls

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

C PROGRAMMING Lecture 5. 1st semester

C PROGRAMMING Lecture 5. 1st semester C PROGRAMMING Lecture 5 1st semester 2017-2018 Program Address Space The Stack The stack is the place where all local variables are stored a local variable is declared in some scope Example int x; //creates

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation CS61, Lecture 10 Prof. Stephen Chong October 4, 2011 Announcements 1/2 Assignment 4: Malloc Will be released today May work in groups of one or two Please go to website and enter

More information

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

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Princeton University Computer Science 217: Introduction to Programming Systems. Data Structures

Princeton University Computer Science 217: Introduction to Programming Systems. Data Structures Princeton University Computer Science 217: Introduction to Programming Systems Data Structures 1 Goals of this Lecture Help you learn (or refresh your memory) about: Common data structures: linked lists

More information

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

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

Memory management. Johan Montelius KTH

Memory management. Johan Montelius KTH Memory management Johan Montelius KTH 2017 1 / 22 C program # include int global = 42; int main ( int argc, char * argv []) { if( argc < 2) return -1; int n = atoi ( argv [1]); int on_stack

More information

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

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation COSC345 2013 Software Engineering Lectures 14 and 15: The Heap and Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines

More information

Binghamton University Dynamic Memory Alloca/on

Binghamton University Dynamic Memory Alloca/on Dynamic Memory Alloca/on Slides credit: Presenta/on based on slides by Dave O halloran/csapp 1 Dynamic memory alloca/on Where is this important? Heap Kernel heap Physical memory allocator Problems are

More information

14. Memory API. Operating System: Three Easy Pieces

14. Memory API. Operating System: Three Easy Pieces 14. Memory API Oerating System: Three Easy Pieces 1 Memory API: malloc() #include void* malloc(size_t size) Allocate a memory region on the hea. w Argument size_t size : size of the memory block(in

More information

TI2725-C, C programming lab, course

TI2725-C, C programming lab, course Valgrind tutorial Valgrind is a tool which can find memory leaks in your programs, such as buffer overflows and bad memory management. This document will show per example how Valgrind responds to buggy

More information

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

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems Deep C Multifile projects Getting it running Data types Typecasting Memory management Pointers Fabián E. Bustamante, Fall 2004 Multifile Projects Give your project a structure Modularized design Reuse

More information

ntroduction to C CS 2022: ntroduction to C nstructor: Hussam Abu-Libdeh (based on slides by Saikat Guha) Fall 2011, Lecture 1 ntroduction to C CS 2022, Fall 2011, Lecture 1 History of C Writing code in

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

Dynamic Memory Management

Dynamic Memory Management Dynamic Memory Management 1 Goals of this Lecture Help you learn about: Dynamic memory management techniques Garbage collection by the run-time system (Java) Manual deallocation by the programmer (C, C++)

More information

Operating systems. Lecture 9

Operating systems. Lecture 9 Operating systems. Lecture 9 Michał Goliński 2018-11-27 Introduction Recall Reading and writing wiles in the C/C++ standard libraries System calls managing processes (fork, exec etc.) Plan for today fork

More information

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation COSC345 Software Engineering The Heap And Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines Virtual memory Swapping

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

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

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

Dynamic Memory Alloca/on: Advanced Concepts

Dynamic Memory Alloca/on: Advanced Concepts Dynamic Memory Alloca/on: Advanced Concepts CS 485 Systems Programming Fall 2015 Instructor: James Griffioen Adapted from slides by R. Bryant and D. O Hallaron (hip://csapp.cs.cmu.edu/public/instructors.html)

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

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

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 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

More information

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

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package Today Dynamic Memory Allocation: Basic Concepts Basic concepts Performance concerns Approach 1: implicit free lists CSci 01: Machine Architecture and Organization October 17th-nd, 018 Your instructor:

More information

Lecture 2: Memory in C

Lecture 2: Memory in C CIS 330:! / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 2:

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

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

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017 CS 137 Part 5 Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors October 25th, 2017 Exam Wrapper Silently answer the following questions on paper (for yourself) Do you think that the problems on

More information

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

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12 Week 9 Part 1 Kyle Dewey Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2 Dynamic Allocation Recall... Dynamic memory allocation allows us to request memory on the fly

More information

C Structures & Dynamic Memory Management

C Structures & Dynamic Memory Management C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail

More information

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

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation Computer Systems Organization (Spring 2017) CSCI-UA 201, Section 3 Instructor: Joanna Klukowska Slides adapted from Randal E. Bryant and David R. O Hallaron (CMU) Mohamed Zahran

More information

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

CS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models CS 61C: Great Ideas in Computer Architecture C Memory Management, Usage Models Instructors: Nicholas Weaver & Vladimir Stojanovic http://inst.eecs.berkeley.edu/~cs61c/sp16 1 Pointer Ninjitsu: Pointers

More information

CMSC 341 Lecture 2 Dynamic Memory and Pointers

CMSC 341 Lecture 2 Dynamic Memory and Pointers CMSC 341 Lecture 2 Dynamic Memory and Pointers Park Sects. 01 & 02 Based on earlier course slides at UMBC Today s Topics Stack vs Heap Allocating and freeing memory new and delete Memory Leaks Valgrind

More information

Agenda. Recap: C Memory Management. Agenda. Recap: Where are Variables Allocated? Recap: The Stack 11/15/10

Agenda. Recap: C Memory Management. Agenda. Recap: Where are Variables Allocated? Recap: The Stack 11/15/10 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Dynamic Memory Management Instructors: Randy H. Katz David A. PaGerson hgp://inst.eecs.berkeley.edu/~cs61c/fa10 1 2 3 Recap: C Memory Management

More information

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

Today. Dynamic Memory Allocation: Basic Concepts. Dynamic Memory Allocation. Dynamic Memory Allocation. malloc Example. The malloc Package Today Dynamic Memory Allocation: Basic Concepts Basic concepts Performance concerns Approach 1: implicit free lists CSci 01: Machine Architecture and Organization Lecture #9, April th, 016 Your instructor:

More information

Dynamic Memory Allocation

Dynamic Memory Allocation 1 Dynamic Memory Allocation Anne Bracy CS 3410 Computer Science Cornell University Note: these slides derive from those by Markus Püschel at CMU 2 Recommended Approach while (TRUE) { code a little; test

More information

Dynamic Memory Allocation I

Dynamic Memory Allocation I Dynamic Memory Allocation I William J. Taffe Plymouth State University Using the Slides of Randall E. Bryant Carnegie Mellon University Topics Simple explicit allocators Data structures Mechanisms Policies

More information

Dynamic Memory Allocation I Nov 5, 2002

Dynamic Memory Allocation I Nov 5, 2002 15-213 The course that gives CMU its Zip! Dynamic Memory Allocation I Nov 5, 2002 Topics Simple explicit allocators Data structures Mechanisms Policies class21.ppt Harsh Reality Memory is not unbounded

More information

Dynamic Memory Allocation: Basic Concepts

Dynamic Memory Allocation: Basic Concepts Dynamic Memory Allocation: Basic Concepts 15-213: Introduction to Computer Systems 19 th Lecture, March 30, 2017 Instructor: Franz Franchetti & Seth Copen Goldstein 1 Today Basic concepts Implicit free

More information

Memory Management in C (Dynamic Strings) Personal Software Engineering

Memory Management in C (Dynamic Strings) Personal Software Engineering Memory Management in C (Dynamic Strings) Personal Software Engineering Memory Organization Function Call Frames The Stack The call stack grows from the top of memory down. sp Available for allocation The

More information

Systems Programming and Computer Architecture ( )

Systems Programming and Computer Architecture ( ) Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture (252-0061-00) Timothy Roscoe Herbstsemester 2016 AS 2016 Dynamic Memory Allocation 1 5: Dynamic memory

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

Processes, Address Spaces, and Memory Management. CS449 Spring 2016

Processes, Address Spaces, and Memory Management. CS449 Spring 2016 Processes, Address Spaces, and Memory Management CS449 Spring 2016 Process A running program and its associated data Process s Address Space 0x7fffffff Stack Data (Heap) Data (Heap) Globals Text (Code)

More information

Reminder: compiling & linking

Reminder: compiling & linking Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object

More information

Midterm Review. What makes a file executable? Dr. Jack Lange 2/10/16. In UNIX: Everything is a file

Midterm Review. What makes a file executable? Dr. Jack Lange 2/10/16. In UNIX: Everything is a file Midterm Review Dr. Jack Lange What makes a file executable? In UNIX: Everything is a file For a file to execute it needs to be marked as special Someone needs to grant it permission to execute Every file

More information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship

More information

Dynamic Memory Alloca/on: Advanced Concepts

Dynamic Memory Alloca/on: Advanced Concepts Dynamic Memory Alloca/on: Advanced Concepts 15-213: Introduc0on to Computer Systems 18 th Lecture, Oct. 26, 2010 Instructors: Randy Bryant and Dave O Hallaron 1 Today Explicit free lists Segregated free

More information

Java's Memory Management

Java's Memory Management Java's Memory Management Oliver W. Layton CS231: Data Structures and Algorithms Lecture 04, Fall 2018 Wednesday September 12 Java %p of the day: Common compila%on errors Class name must MATCH the filename

More information

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

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

Limitations of the stack

Limitations of the stack The heap hic 1 Limitations of the stack int *table_of(int num, int len) { int table[len+1]; for (int i=0; i

More information

ANITA S SUPER AWESOME RECITATION SLIDES

ANITA S SUPER AWESOME RECITATION SLIDES ANITA S SUPER AWESOME RECITATION SLIDES 15/18-213: Introduction to Computer Systems Dynamic Memory Allocation Anita Zhang, Section M UPDATES Cache Lab style points released Don t fret too much Shell Lab

More information

CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III

CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III Instructors: John Wawrzynek & Vladimir Stojanovic http://inst.eecs.berkeley.edu/~cs61c/fa15 1 Review, Last Lecture Pointers are

More information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation Why use Pointers? Share access to common data (hold onto one copy, everybody

More information

Memory Allocation. General Questions

Memory Allocation. General Questions General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

CSE 333 Midterm Exam Sample Solution 7/28/14

CSE 333 Midterm Exam Sample Solution 7/28/14 Question 1. (20 points) C programming. For this question implement a C function contains that returns 1 (true) if a given C string appears as a substring of another C string starting at a given position.

More information

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

CMPS 105 Systems Programming. Prof. Darrell Long E2.371 + CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 7: The Environment of a UNIX process + Introduction + The main() fuction n int main(int argc, char* argv[]); n argc =

More information

Dynamic Memory Allocation: Basic Concepts

Dynamic Memory Allocation: Basic Concepts Dynamic Memory Allocation: Basic Concepts CSE 238/2038/2138: Systems Programming Instructor: Fatma CORUT ERGİN Slides adapted from Bryant & O Hallaron s slides 1 Today Basic concepts Implicit free lists

More information

Dynamic Allocation of Memory

Dynamic Allocation of Memory Dynamic Allocation of Memory Lecture 5 Section 9.8 Robb T. Koether Hampden-Sydney College Wed, Jan 24, 2018 Robb T. Koether (Hampden-Sydney College) Dynamic Allocation of Memory Wed, Jan 24, 2018 1 / 34

More information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic Data Structures. CSCI 112: Programming in C 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

More information

Arrays and Memory Management

Arrays and Memory Management Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted

More information

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

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24 Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program

More information

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

CS 322 Operating Systems Programming Assignment 4 Writing a memory manager Due: November 16, 11:30 PM CS 322 Operating Systems Programming Assignment 4 Writing a memory manager Due: November 16, 11:30 PM Goals To understand the nuances of building a memory allocator. To create a shared library. Background

More information

Memory and C/C++ modules

Memory and C/C++ modules Memory and C/C++ modules From Reading #5 and mostly #6 More OOP topics (templates; libraries) as time permits later Program building l Have: source code human readable instructions l Need: machine language

More information

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

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations Reminder of midterm 1 Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations A New Example to see effect of E++ (better than the one in previous lecture) Purpose of showing

More information

Quick review pointer basics (KR ch )

Quick review pointer basics (KR ch ) 1 Plan for today Quick review pointer basics (KR ch5.1 5.5) Related questions in midterm Continue on pointers (KR 5.6 -- ) Array of pointers Command line arguments Dynamic memory allocation (malloc) 1

More information

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Dynamic Memory Dynamic Memory Allocation Strings September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Pointer arithmetic If we know the address of the first element of an array, we can compute the addresses

More information

Lecture 3 Memory and Pointers

Lecture 3 Memory and Pointers Lecture 3 Memory and Pointers Lets think about memory We can think of memory as a series of empty slots Each cell in the slot will hold 1 Byte To identify which cell something is in we need an identifier.

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c/su06 CS61C : Machine Structures Lecture #6: Memory Management CS 61C L06 Memory Management (1) 2006-07-05 Andy Carle Memory Management (1/2) Variable declaration allocates

More information

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

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store) Lecture 29 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 29: Linked Lists 19-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor: Vlado Keselj Previous

More information

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

Introduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th Introduction to Computer Systems 15 213/18 243, fall 2009 16 th Lecture, Oct. 22 th Instructors: Gregory Kesden and Markus Püschel Today Dynamic memory allocation Process Memory Image %esp kernel virtual

More information

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

2/9/18. Secure Coding. CYSE 411/AIT681 Secure Software Engineering. Agenda. Dynamic Memory Interface. Dynamic Memory Interface Secure Coding CYSE 411/AIT681 Secure Software Engineering Topic #9. Secure Coding: Dynamic Memory Instructor: Dr. Kun Sun String management Pointer Subterfuge Dynamic memory management Integer security

More information

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics Slides adapted (and slightly modified) from: Clark Barrett Jinyang Li Randy Bryant Dave O Hallaron CSCI-UA.0201-001/2 Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics Mohamed

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

More information

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

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

Dynamic Memory Allocation. Gerson Robboy Portland State University. class20.ppt Dynamic Memory Allocation Gerson Robboy Portland State University class20.ppt Harsh Reality Memory is not unbounded It must be allocated and managed Many applications are memory dominated Especially those

More information

CS 241 Honors Memory

CS 241 Honors Memory CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35

More information

A process. the stack

A process. the stack A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes

More information

Dynamic Memory Management! Goals of this Lecture!

Dynamic Memory Management! Goals of this Lecture! Dynamic Memory Management!!! 1 Goals of this Lecture! Help you learn about:! Dynamic memory management techniques! Garbage collection by the run-time system (Java)! Manual deallocation by the programmer

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility, there are four library routines known as memory management

More information

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia

Memory Allocation I. CSE 351 Autumn Instructor: Justin Hsia Memory Allocation I CSE 351 Autumn 2017 Instructor: Justin Hsia Teaching Assistants: Lucas Wotton Michael Zhang Parker DeWilde Ryan Wong Sam Gehman Sam Wolfson Savanna Yee Vinny Palaniappan Administrivia

More information

CS 101: Computer Programming and Utilization

CS 101: Computer Programming and Utilization CS 101: Computer Programming and Utilization Jul-Nov 2017 Umesh Bellur (cs101@cse.iitb.ac.in) Lecture 16: Representing variable length entities (introducing new and delete) A programming problem Design

More information

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1 C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...

More information