Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

An introduction to pointers in c
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.
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.
CSE 251 Dr. Charles B. Owen Programming in C1 Dynamic Memory Allocation Dynamic memory allocation – How to allocate memory for variables (esp. arrays/strings)
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
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.
1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the design and concepts behind pointer arithmetic ❏ To write.
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{
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
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’;
Introduction to C Programming CE Lecture 18 Dynamic Memory Allocation and Ragged Arrays.
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.
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.
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
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.
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.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
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.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
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.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Stack and Heap Memory Stack resident variables include:
Day 03 Introduction to C.
Day 03 Introduction to C.
CSCI206 - Computer Organization & Programming
Lecture 6 C++ Programming
Dynamic Memory Allocation
Circular Buffers, Linked Lists
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Dynamic Memory A whole heap of fun….
C Programming Lecture-8 Pointers and Memory Management
Dynamic Memory – A Review
Presentation transcript:

Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College

2.1 INTRODUCTION So far, fixed amount of memory is used Program could not increase or decreased memory during runtime Dynamic memory allow you to create and use data structure that can grow and shrink.

2.2 Static and Dynamic Memory With static memory, you define the maximum amount of space required.  char a[1000]; There no way to change amount of memory in runtime. Dynamic memory comes in blocks without names, just address.

2.2 Static and Dynamic Memory (cont.) malloc() function is used to request a block of certain size (in byte). int memsize; // memsize get a value at runtime x=malloc(memsize);

2.2 Static and Dynamic Memory (cont.) free() function is used to return it (memory) to the pool. free(x); Every call to malloc() must be balanced by a call to free().

2.2 Static and Dynamic Memory (cont.) malloc() return the starting address of the newly allocated block. The starting address to be stored in pointer of type void; Void *x; A void pointer variable can store address of any type. Refer to figure 10.1 Refer to script 10.1

Figure 10.1 xmemsize

/* memory.c - Script 10.1 */ #include int main (void) {/* Declare a void pointer variable. */ void *x; /* Request a block of memory with 1000 bytes. */ x = malloc (1000); /* Print out the starting address of the memory block. */ cout<<"Starting block address: “<< x; /* Return the block to the pool. */ free(x); x = NULL; /*Pause and wait for input before terminating. */ //getchar(); return 0; }

2.2 Static and Dynamic Memory (cont.) Void *x; X= malloc(size); Free(x); X=NULL; The pointer should be set to NULL after freed.

2.3 TYPE CAST The void pointer variable allows you to store and retrieve any kind of address (integer, float, double, string etc). Since the pointer can point to anything, the system cannot know if it should read or write a 1-byte or a 4-byte integer, or something completely different.

2.3 TYPE CAST (cont.) System need to be informed- what kind of data is stored. Void *x; (int *)x; It is called type-cast. Script 10.2

/* typecast.c - Script 10.2 */ #include int main (void) { /* Define and initialize a void pointer variable. */ void *x = NULL; /* Request a block of memory large * enough to hold an integer. */ x = malloc(sizeof(int)); /* We have omitted the check for NULL * here. You must always check for a NULL * return value from malloc(). */ /* Print out the starting address of the memory block. */

cout<<"Starting address: “<< x<<endl; /* Store an integer in the new memory block. */ *(int *)x = 1234; /* Print the value. */ cout<<"Value stored in the memory block: “<< *(int*)x); /* Return the block to the pool. */ free(x); x = NULL; /* Pause and wait for input before terminating. */ getchar(); return 0; }

2.4 ALLOCATING ARRAYS OF DYNAMIC SIZE The example discussed in previous still consider static memory. The amount of should be determine and request during runtime. Refer to script 10.3

/* array.c - Script 10.3 */ #include int main (void) { /* Define an integer pointer variable. */ int *x = NULL; /* Define two integer variables. */ int i, count; /* Prompt for the number of items. Store * the user's reply in the count variable. */ cout<<"Number of items? "; cin>>count;

/* Request a block of memory large * enough to hold the requested number * of integers. */ x = (int*)malloc(count * sizeof(int)); /* We have omitted the check for NULL * here. You must always check for a NULL * return value from malloc(). */ /* Store a random number in every slot * of the array. */ for (i = 0; i < count; i++) { x[i] = rand(); }

/* Print all values in the array. */ for (i = 0; i < count; i++) { cout<<“The value of array element “<< i <<“ is “<<x[i] <<endl; } /* Return the block to the pool. */ free(x); x = NULL; /* Pause and wait for input before terminating. */ return 0; }

2.5 Resizing a Block of Memory Sometime you have to resize a block of dynamic memory after you have already stored data in it. The C++ library provides the realloc() function for this purpose. void *x *y; x=malloc(1000); // initial block Y= realloc(x,2000);// doubled

2.5 Resizing a Block of Memory(2) realloc() attempts to grow the original size to accommodate the new requested size. If successful:- it returns the block’s unchanged. If it not possible to grow the old block (not enough adjacent free space in memory):- realloc() will instead allocate a new block in a different part of memory; copy all over of the old data to the new block and return the address of that new block.

2.5 Resizing a Block of Memory(3) Upon failure, the realloc() returns the NULL pointer instead. Script 10.4

Stop! Do exercise This code is bad, why? void *x ; x=malloc(1000); // initial block x= realloc(x,2000);// doubled If realloc() fails and return a NULL pointer, the initials address of the memory block returned by the malloc(1000) call is lost. Since that value can longer be passed to free(), the originally reserved memory cannot be reclaimed until the program terminates. This is called memory leak.

Summary Dynamic memory allow you to create and use data structure that can grow and shrink. malloc() function is used to request a block of certain size (in byte). free() function is used to return it (memory) to the pool.

Summary(2) realloc adjusts the size of the allocated block to size, copying the contents to a new location if necessary.