Memory Management I. two kinds of memory: stack and heap

Similar documents
Dynamic memory allocation

Multidimensional Arrays I

DAY 3. CS3600, Northeastern University. Alan Mislove

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

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

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Understanding Pointers

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

Dynamic memory allocation (malloc)

Memory Management. CSC215 Lecture

POINTER AND ARRAY SUNU WIBIRAMA

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

Composition I. composition is a way to combine or compose multiple classes together to create new class

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

Lecture 8 Dynamic Memory Allocation

Memory (Stack and Heap)

Dynamic Allocation of Memory

Dynamic memory. EECS 211 Winter 2019

Dynamic Allocation in C

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Pointers, Dynamic Data, and Reference Types

Dynamic Data Structures. CSCI 112: Programming in C

Arrays and Memory Management

Kurt Schmidt. October 30, 2018

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

A process. the stack

CS 11 C track: lecture 5

CSC 1600 Memory Layout for Unix Processes"

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

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Dynamic Allocation in C

Dynamic Allocation of Memory

Heap Arrays. Steven R. Bagley

Intermediate Programming, Spring 2017*

Processes. Johan Montelius KTH

Common Misunderstandings from Exam 1 Material

Fall 2018 Discussion 2: September 3, 2018

CS61C : Machine Structures

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

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

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

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

Dynamic Memory Allocation and Command-line Arguments

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

Reminder: compiling & linking

Quick review pointer basics (KR ch )

C Structures & Dynamic Memory Management

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

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

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

TI2725-C, C programming lab, course

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

Lecture 04 Introduction to pointers

CS201 Some Important Definitions

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

ECE551 Midterm Version 2

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

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

Section 2: Processes

14. Memory API. Operating System: Three Easy Pieces

Dynamic Memory. R. Inkulu (Dynamic Memory) 1 / 19

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

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

Content. In this chapter, you will learn:

CSE 333 Midterm Exam 5/10/13

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

Memory Management. CS449 Fall 2017

Lecture 20 Notes C s Memory Model

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

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

High Performance Programming Programming in C part 1

Pointers and File Handling

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.

CS61C : Machine Structures

Writing Functions in C

Systems Programming and Computer Architecture ( )

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

Operating System Labs. Yuanbin Wu

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Creating a String Data Type in C

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

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

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Pointers. Introduction

CS 222: Pointers and Manual Memory Management

Lecture 20 C s Memory Model

HW1 due Monday by 9:30am Assignment online, submission details to come

CS24 Week 2 Lecture 1

Fundamental of Programming (C)

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C & Data Structures syllabus

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

Dynamic Memory Allocation

CS 610: Intermediate Programming: C/C++ Making Programs General An Introduction to Linked Lists

CSCI 171 Chapter Outlines

Memory and C/C++ modules

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

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

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

Heap Arrays and Linked Lists. Steven R. Bagley

Transcription:

Memory Management I two kinds of memory: stack and heap stack memory: essentially all non-pointer (why not pointers? there s a caveat) variables and pre-declared arrays of fixed (i.e. fixed before compilation) length live in the stack all local (and non-static) variables within a function live on the stack and they die automatically when the function exits heap memory: dynamically allocated memory (hold your breath, its coming your way!) reside in the heap and they do not die automatically, you need to allocate and dellacote them June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 1

Memory Management II when to use which? suppose your job is to store and do some stuff with the first N-natural numbers, where N is used specified suppose beforehand you fix an upper limit and ask of the user to only specify N < 10000 then you may declare: #define MAX_NN 10000 int iarr[max_nn]; note fixing an upper limit is kind of restrictive so you may decide to take a postive number, say, nn, as an input from the user and work with an array of length nn then you may declare (hold on, details coming later): int nn, *iarr; /* scanf the value of nn here */ iarr = (int *) malloc(nn * sizeof(int)); June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 2

Memory Management III the following two snippets do not do the same thing: below MAX_NN is literally substitued by 10000 before compilation i.e. pretend that manually you had typed 10000 in your code wherever you see MAX_NN (why do this? it avoids magic numbers, coming later!) #define MAX_NN 10000 int iarr[max_nn]; below max_nn (note C is case-sensitive and hence max_nn and MAX_NN are different symbols ) is a variable and hence the size of iarr is also variable int max_nn = 100000, iarr[max_nn]; the above is not allowed by gcc -ansi -pedantic i.e. in ANSI C but C99 allows it so plain gcc without those options would compile it just fine do not use this feature: is the right place to use dynamic memory management with malloc( ), free( ) and the sort June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 3

Memory Management IV example of stack memory: #define SMALL_LEN 50 double * mem_stack1 (void) { double dval; return &dval; double * mem_stack2 (void) { double dval[small_len]; return dval; June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 4

Memory Management V heap memory: allocation: void * malloc(size_t size); note malloc returns a void * pointer but, say, we want to allocate space for SMALL_LEN many doubles, here s how you do it: get the right amount of space: malloc(small_len * sizeof(double)) cast the void * pointer to a pointer to double: (double *) malloc(small_len * sizeof(double)) note, (double *) is the cast operator, in general (typename) foo casts variable foo to type typename June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 5

Memory Management VI heap memory: deallocation: void free(void *ptr); note free takes a void * as an argument thus any pointer could be passed to it: double *dval_arr = NULL; dval_arr = (double *) malloc(small_len * sizeof(double)); free(dval_arr); note however though, free only frees the space pointed to by dval_arr, it doesn t free dval_arr itself, what does that mean? the above thing is called the problem of dangling pointers June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 6

Memory Management VII example of heap memory: #define SMALL_LEN 50 double * mem_heap1 (void) { double *dval_arr; dval_arr = (double *) malloc(small_len * sizeof(double)); return dval_arr; June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 7

Memory Management VIII the stack memory may/may not, we don t know, cause runtime error giving Segmentation Fault the heap memory if managed properly would work just fine remember to always deallocate heap memory which you wouldn t be using anymore failure to properly deallocate causes what is known as memory-leak which makes the program slow and it ultimately gets killed by the operating system #define BIG_LEN 200000 /* Memory leak example: don t do something like the following */ for (ii = 0; ; ) { printf("count = %d\n", ++ii); dval_arr = (double *) malloc(big_len * sizeof(double)); June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 8

Memory Management IX example stack memory mis-usage and heap memory usage: int main (int argc, char **argv) { int ii; double *dval_arr = NULL; dval_arr = mem_stack1( ); for (ii = 0; ii < SMALL_LEN; ++ii) { dval_arr[ii] = 10 * ii; printf("dval_arr[%d] = %g\n", ii, dval_arr[ii]); dval_arr = NULL; dval_arr = mem_heap1( ); for (ii = 0; ii < SMALL_LEN; ++ii) { dval_arr[ii] = 10 * ii; printf("dval_arr[%d] = %g\n", ii, dval_arr[ii]); free(dval_arr); dval_arr = NULL; return 0; June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 9

Memory Management X how to guard against memory leakage? do the proper book-keeping whenever you use a function and there are pointers involved either in the arguement(s) or in the return value find out who is responsible for the memory of those pointers: the callee: char * strdup(const char *str); here the callee allocates memory for the return value or the caller char * stpcpy(char *dst, const char *src); here the caller allocates memory for dst and makes sure its big enough to hold a copy of src June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 10

Memory Management XI other memory allocation tools: allocating cleared space: allocate memory and clear it to zero void * calloc (size_t count, size_t eltsize); resizing memory: change (increase or decrease) the size of the block whose address is ptr to be newsize void * realloc (void *ptr, size_t newsize); June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 11

Memory Management XII example of calloc: dval_arr = (double *) calloc(small_len, sizeof(double)); example of realloc: dval_arr = (double *) malloc(small_len * sizeof(double)); dval_arr = (double *) realloc(dval_arr, 2 * SMALL_LEN * sizeof(double)); or dval_arr = (double *) calloc(small_len, sizeof(double)); dval_arr = (double *) realloc(dval_arr, 2 * SMALL_LEN * sizeof(double)); June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 12

Memory Management XIII checking allocated memory: malloc, calloc and realloc all may return NULL to indicate failure to acquire/resize memory so we need to always check the return value of these functions: double * mem_heap2 (void) { double *dval_arr; dval_arr = (double *) malloc(small_len * sizeof(double)); if (dval_arr == NULL) { printf("malloc falied to acquire memory: aborting...\n"); abort( ); return dval_arr; June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 13

Code Files prog9.c June 29, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 14