Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Similar documents
Arrays and Pointers in C & C++

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Linked Lists in C and C++

Memory (Stack and Heap)

Lecture 8 Dynamic Memory Allocation

C Structures & Dynamic Memory Management

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

Dynamic Memory Allocation I

Structures, Unions, and Typedefs

Dynamic memory allocation

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:

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

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

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Programming. Pointers, Multi-dimensional Arrays and Memory Management

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

CSC 1600 Memory Layout for Unix Processes"

Memory Management. CSC215 Lecture

CS 11 C track: lecture 5

Dynamic memory allocation (malloc)

Classes, Constructors, etc., in C++

Memory Management. CS449 Fall 2017

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

POINTER AND ARRAY SUNU WIBIRAMA

Dynamically Allocated Memory in C

Dynamic Memory Allocation I Nov 5, 2002

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

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

(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 Management

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

Dynamic Data Structures. CSCI 112: Programming in C

Fall 2018 Discussion 2: September 3, 2018

Your first C and C++ programs

Memory Allocation. General Questions

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

Dynamic Allocation in C

Dynamic Allocation of Memory

Quick review pointer basics (KR ch )

Content. In this chapter, you will learn:

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

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

Dynamic Memory Allocation

Dynamic Memory Allocation: Basic Concepts

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

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

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

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

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

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

14. Memory API. Operating System: Three Easy Pieces

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

Dynamic Memory Allocation

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

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

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

COSC345 Software Engineering. The Heap And Dynamic Memory Allocation

Exception Handling in C++

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

Dynamic Memory Allocation: Basic Concepts

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

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

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

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

ANITA S SUPER AWESOME RECITATION SLIDES

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:

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

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

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

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

Binary Trees (and Big O notation)

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

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

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

Derived Classes in C++

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

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

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

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

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

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

ME964 High Performance Computing for Engineering Applications

Advanced Unix Programming Module 06 Raju Alluri spurthi.com

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

Introduction to C++ Introduction to C++ 1

Arrays and Pointers (part 1)

Agenda. Dynamic Memory Management. Robert C. Seacord. Secure Coding in C and C++

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

CS61C : Machine Structures

Dynamic Memory Allocation

Arrays, Pointers and Memory Management

Kurt Schmidt. October 30, 2018

Processes. Johan Montelius KTH

Intermediate Programming, Spring 2017*

DAY 3. CS3600, Northeastern University. Alan Mislove

A process. the stack

Structures, Unions, and Enumerations

COSC Software Engineering. Lecture 16: Managing Memory Managers

Transcription:

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 and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) 1

Problem What do you do if: the size of an array is not known until run time? OR a function must return an array that it creates? How can we manipulate variable-length arrays and pass them around our programs? Answer: Use dynamically allocated storage in The Heap! 2

Definition The Heap A region of memory provided by most operating systems for allocating storage not in Last in, First out discipline I.e., not a stack Must be explicitly allocated and released May be accessed only with pointers Remember, an array is equivalent to a pointer Many hazards to the C programmer 3

Dynamic Data Allocation 0xFFFFFFFF stack (dynamically allocated) SP address space 0x00000000 heap (dynamically allocated) global and static data program code (text) PC CS-2303, A-Term 2012 Arrays and Pointers 4

Allocating Memory in The Heap See <stdlib.h> void *malloc(size_t size); free() knows size of chunk void free(void *ptr); allocated by malloc() or void *calloc(size_t nmemb, size_t size); calloc() void *realloc(void *ptr, size_t size); malloc() allocates size bytes of memory from the heap and returns a pointer to it. NULL pointer if allocation fails for any reason free() returns the chunk of memory pointed to by ptr back to the heap Must have been allocated by malloc() or calloc() 5

Notes calloc() is just a variant of malloc() malloc() is analogous to new in C++ and Java new in C++ actually calls malloc() free() is analogous to delete in C++ delete in C++ actually calls free() Java does not have delete uses garbage collection to recover memory no longer in use 6

Example usage of malloc() and free() #include <stdlib.h> int PlayGame(int board[], int arraysize); int main(){ int s, t; int A[]; s = ; /* determine size of array from input */ A = malloc(s * sizeof(int)); ; t = PlayGame(A, s); free(a); return t; } 7

Alternate version of malloc() and free() #include <stdlib.h> int PlayGame(int *board, int arraysize); int main(){ int s, t; int *A; s = ; /* determine size of array from input */ A = malloc(s * sizeof(int)); ; t = PlayGame(A, s); free(a); return t; } 8

Generalization malloc() and free() are used whenever you need a dynamically sized array whenever you need an array that does not follow last in, first out rule of The Stack Valid in all versions of C See p. 167 of K&R ( 7.8.5) 9

malloc vs. calloc void *malloc(size_t #ofbytes) Takes number of bytes as argument Aligned to largest basic data type of machine» Usually long int Does not initialize memory Returns pointer to void void *calloc(size_t #ofitems, size_t sizeofitem) Takes number of # of items and size as argument Initializes memory to zeros; returns pointer to void calloc(n, itemsize) malloc(n * itemsize) Plus initialization to zero 10

realloc() void *realloc(void *p, size_t newsize) Changes the size of a malloc ed piece of memory by allocating new area (or changing size of old area) May increase or decrease size Data copied from old area to new area If larger, extra space is uninitialized free(p) i.e., frees old area (if new area different from old) Returns pointer to void of new area See p. 252 of K&R Rarely used in C programming! 11

Definition Memory Leak The steady loss of available memory in Heap due to program forgetting to free everything that was malloc ed. Bug-a-boo of most large C and C++ programs If you overwrite or lose the value of a pointer to a piece of malloc ed memory, there is no way to find it again! Automatically creating a memory leak Killing the program frees all memory! 12

Questions? 13

Multi-Dimensional Arrays int D[10][20] A one-dimensional array with 10 elements, each of which is an array with 20 elements I.e., int D[10][20] /*[row][col]*/ Last subscript varies the fastest I.e., elements of last subscript are stored contiguously in memory Also, three or more dimensions 14

Limitations of Worcester Polytechnic Carnegie Institute Mellon Multi-Dimensional Arrays C supports only fixed size multi-dimensional arrays Rows stored contiguously in memory Compiler must know how many elements in a row Cannot pass an array to a function with open-ended number of elements per row void f(int A[][20], int nrows); /*okay*/ void f(int A[10][], int ncols); /*NOT okay */ void f(int A[][], int nrows, int ncols); /*also NOT okay */ Same for three or more dimensions! 15

Dynamic Two-Dimensional Arrays Array of pointers, one per row Each row is a one-dimensional array int x, y; /* x = #rows, y = #columns */ int **B = calloc(x, sizeof(int *)); for (i = 0; i < x; i++) B[i] = calloc(y, sizeof(int)); /* to access element of row i, column j */ B[i][j] 16

Why does this work? int **B means the same as int *B[]; I.e., B is an array of pointers to int Therefore, B[i] is a pointer to int But if A is a pointer to int, then A[j] is the jth integer of the array A Substitute B[i] for A Therefore, B[i][j] is the jth integer of the ith row of B 17

Why does this work? (continued) When expression contains B[i][j], compiler generates code resembling int *temp = B + i; *(temp + j); in order to access this element 18

Alternative Method int x, y; /* x = #rows, y = #columns */ int **B = calloc(x, sizeof(int *)); int elements[] = calloc(x*y, sizeof(int)); for (i = 0; i < x; i++) B[i] = &elements[i*y]; /* to access element of row i, column j */ B[i][j] Why does this work? Exercise for the student! 19

Arrays as Function Parameters (again) void init(float A[], int arraysize); void init(float *A, int arraysize); Are identical function prototypes! Pointer is passed by value I.e. caller copies the value of a pointer of the appropriate type into the parameter A Called function can reference through that pointer to reach thing pointed to 20

Arrays as Function Parameters (continued) void init(float A[][], int rows, int columns); void init(float **A, int rows, int columns); Not Identical! Compiler complains that A[][] in header is incompletely specified Needs to know number of columns As if constant! Must use pointer notation in header or declaration In body of init, A[i][j] is still acceptable Worcester Polytechnic Carnegie Institute Mellon CS-2303, A-Term 2012 Dynamic Memory Allocation 21

Questions? 22