1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Management
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings)
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Informática II Prof. Dr. Gustavo Patiño MJ
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
UBC104 Embedded Systems Variables, Structures & Pointers.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
1 Records Record aggregate of data elements –Possibly heterogeneous –Elements/slots are identified by names –Elements in same fixed order in all records.
University of Washington Today Finished up virtual memory On to memory allocation Lab 3 grades up HW 4 up later today. Lab 5 out (this afternoon): time.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
ISBN Chapter 6 Data Types Pointer Types Reference Types Memory Management.
ECE Application Programming
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Dynamic Memory Management Jennifer Rexford 1. 2 Goals of this Lecture Dynamic memory management techniques Garbage collection by the run-time system (Java)
Sections Basic Data Structures. 1.5 Data Structures The way you view and structure the data that your programs manipulate greatly influences your.
Pointers and Arrays Dynamic Variables and Arrays.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
CSE 220 – C Programming malloc, calloc, realloc.
ENEE150 Discussion 07 Section 0101 Adam Wang.
Programmazione I a.a. 2017/2018.
CSCI206 - Computer Organization & Programming
Storage.
CSC215 Lecture Memory Management.
Memory Allocation CS 217.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory.
Comp 208 Computers in Engineering Yi Lin Fall, 2005
Dynamic Memory – A Review
Presentation transcript:

1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material

2 C’s data structures have fixed size known at compile time –char – 1 byte –short – 2 bytes –int – 4 bytes –float – 4 bytes –double – 8 bytes –Array size must be known at compile time and is fixed int A[10]; –Structure and Union sizes are also fixed Often the actual size of an array is not known until the execution time! Dynamic Memory Allocation: Why?

3 Consider a simple program that takes some number of integers and performs some operation on them The question that arises is the size of the array that will store the integers Dynamic Memory Allocation: Why?

4 The usual approach is to declare an array that is as big as it ever will need to be –#define N /* at most 1 million numbers */ –int A[N]; Adv: Simple Disadvantages –Even if we manipulate only 100 numbers, we still reserve space for 1 million integers, but use only the first 100, wasting the rest –Cannot handle input larger than 1 million Solution –Dynamically allocate as much space as needed during execution Dynamic Memory Allocation: Why?

5 C library provides 2 functions that perform dynamic memory allocation and de-allocation Dynamic Memory Allocation Functions void *malloc(int size); /* Allocates size many bytes of contiguous memory * and return a pointer to the beginning of the * memory chunk. * Returns NULL if the memory cannot be allocated */ void free(void *pointer); /* Deallocates memory previously allocated by malloc * pointed to by pointer */

6 Example (1) char *p = NULL; p = (char *)malloc(50); if (p == NULL){ printf(“Out of memory\n”); exit(1); } /* end-if */ p[0] = ‘a’; p[1] = ‘b’; p[2] = ‘\0’; printf(“p= \n”, p); /* Will print p= */ 50 bytes long p p points to a 50 byte long contiguous memory chunk How you use this memory is application dependant

7 Example (2) char *pi = NULL; /* Allocate space for 25 integers */ pi = (int *)malloc(sizeof(int)*25); pi[0] = 5; pi[1] = 2; free(pi); /* Deallocate space */ What if we want to allocate space for say 25 integers?

8 Memory Leaks It is your responsibility to deallocate memory chunks when you are done with them If you forget to deallocate the space, it will still be part of your address space, but you cannot access it –This is called a memory leak

9 Memory Leaks: Example /* Allocate space for 10 ints */ pi = malloc(10*sizeof(int)); pi[0] = 2;.. /* Allocate space for 20 ints without deallocating * space for the previous 10 ints */ pi = malloc(20*sizeof(int)); pi[0] = 3; /* Notice that we lost the handle to the previous * memory chunk. That space has leaked out of the * program. If your program runs long enough, * leaking memory like this continuously, it * will be out of memory. */

10 Dangling Pointer Problem char *p, *q; p = (char *)malloc(10); q = p; p[0] = ‘A’; q[1] = ‘B’;.. free(p); q[0] = ‘X’; /* Wrong! */ It is illegal to use memory that has been freed Consider the following program 10 bytes long p q At this point the memory chunk pointed to by either p or q is invalid. It has been freed and cannot be accessed P & q are called dangling pointers

11 Dangling Pointers (cont) To avoid memory leaks and dangling pointers, programming languages such as Java, C# handle dynamic memory deallocation automatically –This is called garbage collection –The runtime environment of Java and C# has automatic garbage collectors –Thus programmers do not have to deallocate memory The disadvantage of this approach is speed –Java, C# is slower compared to C, C++ –safety  versus  speed tradeoff