Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Functions and scope Confidence In scope Reference: K&K textbook, Chapter 4.
Introduction to Memory Management. 2 General Structure of Run-Time Memory.
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.
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
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.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Pointers A pointer is a reference to another variable (memory location) in a program –Used to change variables inside a function (reference parameters)
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
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:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Run-Time Storage Organization
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Pointers Applications
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Outline Midterm results Static variables Memory model
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Lecture 13 Static vs Dynamic Memory Allocation
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
Basic Semantics Associating meaning with language entities.
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.
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.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Dynamic memory allocation and Pointers Lecture 4.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
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.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Stack and Heap Memory Stack resident variables include:
Lesson One – Creating a thread
CSCI206 - Computer Organization & Programming
Dynamic Memory Allocation
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Topic 3-b Run-Time Environment
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory A whole heap of fun….
CS111 Computer Programming
Chapter 7: User-Defined Functions II
Dynamic Memory A whole heap of fun….
C Programming Lecture-8 Pointers and Memory Management
Run-time environments
Presentation transcript:

Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation Java dynamic allocation example The malloc() function 'C' dynamic allocation example

Conventional data declarations These all require that the amount of memory needed in bytes is known at compile time. There are 3 types: 1. Global memory variables 2. Automatic memory variables 3. Static memory variables

Global memory variables These are memory variables declared outside of the functions and accessible to all functions without having to be declared more than once or passed as parameters. Justified in few cases, but in others this breaks modularisation of data and complicates and hides communication between functions. Misuse of globals causes difficult to find bugs and more buggy programs. typedef struct student { int startyear; char name[30]; } STUDENT; STUDENT sdn[50]; /* global array of student records */ int main(void){...

Automatic memory variables Automatic memory variables use memory which is automatically allocated at runtime when a function is entered, and this memory is automatically recovered (garbage collected) when the function exits. float cube(float value){ /* parameters are automatic*/ float result; /* automatic memory variable */...

Static memory variables Static memory variables are declared using the static keyword. As with automatic variables, static data are also useful for modularising data within functions, enabling clean and visible interfaces between functions and easier debugging. Unlike automatic variables, they exist for as long as the entire program runs. They are useful for data made accessible through pointers elsewhere, and for values which needs to be preserved between calls to the same function. void printprime(int prime){ /* prints primes in rows of 8 columns */ static int col=0; /* only initialised once */ col++; /* add 1 each time function is called */...

Incorrect attempt at dynamic memory sizing The compiler must know how much memory to allocate for the above 3 memory types. This means that arrays declared using approaches such as: float fa[N]; require that N is a constant the value of which is known at compile time.

Incorrect attempt at dynamic memory sizing This approach will not work int size; float *fp; printf("enter number of elements\n"); scanf("%d",&size); fp=makearray(size);... float *makearray(int size){ static float fa[size]; /* wrong !! */ return fa; }

Requirement for dynamic memory allocation A program is likely to have to optimise use of memory. Flexibility requires that the source code should not need to be changed to match the amount of data to the memory available and recompilation with different sizes for data structures might not be practical. You might want to use the same program on a mainframe capable of handling millions of records or on an embedded system where memory only exists for a few thousand. In some programs the application needs allocation and freeing of memory to be under program control at points in the running program not matching the rules for the other memory types described so far.

Java Example Other programming languages with object oriented features typically use the new keyword to allocate space for, and return references to non-trivial newly created objects. BufferedReader in=Text.open(System.in); // allocate input stream, requires Text class Text.prompt("how many frequencies ?"); // prompt user int numf=Text.readInt(in); // read number of frequencies required int frequencies[] = new int[numf]; // frequencies is now an array of integers

'C' Example 1 The 'C' programming language uses the malloc() function for this purpose. int *frequencies, numf; /* pointer to start of and size of array */ printf("how many frequencies ?\n"); /* prompt user */ scanf("%d",&numf); /* read number of frequencies required */ frequencies = (int*) malloc(sizeof(int)*numf); /* frequencies now points to an array of integers */

The malloc() function void *malloc(size_t); /* function prototype */ malloc() requires one parameter of type size_t, this is an integral type such as might be returned by sizeof(). This parameter is the amount of memory which malloc() is required to allocate in bytes. malloc() returns a void pointer, which is a valid address to the contiguous block of memory allocated, but of no specific type, because malloc() doesn't know what data type the memory allocated will be used for.

Example call of malloc frequencies = (int*) malloc(sizeof(int)*numf); The void pointer returned is cast to become a pointer to int using the (int*) cast operator, so that the memory allocated will be used to store integers. The size in bytes of an integer variable is returned by sizeof(int). This is multiplied by numf, the number of integers required, so the number of bytes needed for the integer array are allocated. The pointer frequencies may now be used to access an array of numf integers. The first integer is addressed as frequencies and accessed as frequencies[0] and the last integer in the array may be accessed as frequencies[numf-1]

Using the free() function Most production programs written in 'C' use dynamic memory for most program data because of the flexibility this allows. But for a server program running 24x7x365, memory allocated for data to meet each client request has to be freed after use or the memory leakage will kill the program. When the data are no longer needed, the free function is called to free the allocation: free(pointer_variable); /* garbage collection R US */

More 'C' Examples