CSE1303 Part A Data Structures and Algorithms Lecture A6 – Dynamic Memory.

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Dynamic memory allocation
Carnegie Mellon 1 Dynamic Memory Allocation: Basic Concepts : Introduction to Computer Systems 17 th Lecture, Oct. 21, 2010 Instructors: Randy Bryant.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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{
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M.
Informática II Prof. Dr. Gustavo Patiño MJ
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’;
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A6 – Dynamic Memory.
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CSE1303 Part A Data Structures and Algorithms Lecture A7 – Nodes and Linked Structures.
Topic 2 Pointers CSE1303 Part A, Summer Semester,2002 Data Structures and Algorithms.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A2 – Pointers (Revision)
Lecture 2 Pointers Pointers with Arrays Dynamic Memory Allocation.
CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
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.
Memory Layout C and Data Structures Baojian Hua
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CS3012: Formal Languages and Compilers The Runtime Environment After the analysis phases are complete, the compiler must generate executable code. The.
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.
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.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
1 Program Layout in memory –Code –Data Global variables –Stack Local variables & function Invocation Frames –Heap Dynamically allocated memory Today’s.
14/3/02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures, ADT Lecture 25 14/3/2002.
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.
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.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Kymberly Fergusson WELCOME CSE1303 Part A Data Structures and Algorithms Summer 2002.
© 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.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
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.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Memory allocation & parameter passing
Stack and Heap Memory Stack resident variables include:
Dynamic Allocation Review Structure and list processing
Day 03 Introduction to C.
Introduction to Programming
ENEE150 Discussion 07 Section 0101 Adam Wang.
2016.
Day 03 Introduction to C.
CSCI206 - Computer Organization & Programming
Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M.
Dynamic Memory Allocation
Memory Allocation CS 217.
Review & Lab assignments
C Programming Lecture-8 Pointers and Memory Management
Pointers, Dynamic Data, and Reference Types
Module 13 Dynamic Memory.
Presentation transcript:

CSE1303 Part A Data Structures and Algorithms Lecture A6 – Dynamic Memory

2 Overview Virtual Memory What is Dynamic Memory ? How to find the size of objects. Allocating memory. Deallocating memory.

3 Virtual Memory Text Segment Data Segment Stack segment program instructions static and dynamic data local variables, parameters free memory

4 Virtual Memory Text Segment Static data Heap Stack segment global variables, etc. dynamic data

5 Virtual Memory Text Segment Static data Heap Stack segment memory is allocated and deallocated as needed

6 What is Dynamic Memory? Memory which is allocated and deallocated during the execution of the program. Types: –data in run-time stack –dynamic data in the heap

7 Example: Run-Time Stack Memory is allocated when a program calls a function. – parameters – local variables – where to go upon return Memory is deallocated when a program returns from a function.

8 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack

9 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b

10 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x

11 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line 16

12 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line 16 result

13 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line result

14 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line result

15 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b

16 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b

17 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack

18 #include int factorial (int x) { if (x == 0) { return 1; } return x * factorial (x –1); } void main() { int n; printf(“Enter a number: \n”); scanf(“%d”, &n); printf(“Factorial: %d\n”, factorial(n); }

19 How much memory to allocate? The sizeof operator returns the size of an object, or type, in bytes. Usage: sizeof( Type ) sizeof Object

20 Example 1: int n; char str[25]; float x; double numbers[36]; printf(“%d\n”, sizeof(int)); printf(“%d\n”, sizeof n); n = sizeof str; n = sizeof x; n = sizeof(double); n = sizeof numbers;

21 Notes on sizeof Do not assume the size of an object, or type; use sizeof instead. In DOS: 2 bytes (16 bits) In GCC/Linux: 4 bytes (32 bits) In MIPS: 4 bytes (32 bits) Example: int n;

22 #include #define MAXNAME 80 #define MAXCLASS 100 struct StudentRec { char name[MAXNAME]; float mark; }; typedef struct StudentRec Student; Example 2:

23 int main() { int n; Student class[MAXCLASS]; n = sizeof(int); printf(“Size of int = %d\n”, n); n = sizeof(Student); printf(“Size of Student = %d\n”, n); n = sizeof class; printf(“Size of array class = %d\n”, n); return 0; } Example 2 (cont.):

24 Notes on sizeof (cont.) The size of a structure is not necessarily the sum of the sizes of its members. Example: struct cardRec { char suit; int number; }; typedef struct cardRec Card; Card hand[5]; printf(“%d\n”, sizeof(Card)); printf(“%d\n”, sizeof hand); “alignment” and “padding” 5*sizeof(Card)

25 Dynamic Memory: Heap Memory can be allocated for new objects. Steps: determine how many bytes are needed allocate enough bytes in the heap take note of where it is (memory address)

26 #include main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } Example 1: NULL stack aPtr heap

27 #include main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } heap 0x3a04 NULL stack aPtr 0x3a04 Example 1: “type cast”

28 #include main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } 5 heap 0x3a04 stack aPtr 0x3a04 Example 1:

29 #include main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } 0x3a04 stack aPtr Example 1: heap deallocates memory

30 #include main() { int* aPtr; int* bPtr; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; bPtr = (int*)malloc(sizeof(int)); *bPtr = 8; free(aPtr); aPtr = bPtr; bPtr = (int*)malloc(sizeof(int)); *bPtr = 6; free(bPtr); } Example 2:

31 Allocating Memory NeedNeed to include stdlib.h malloc(n) returns a pointer to n bytes of memory. AlwaysAlways check if malloc has returned the NULL pointer. ApplyApply a type cast to the pointer returned by malloc.

32 Deallocating Memory free( pointer ) deallocates the memory pointed to by a pointer. It does nothing if pointer == NULL. pointer must point to memory previously allocated by malloc. ShouldShould free memory no longer being used.

33 main() { Student* studentPtr = NULL; studentPtr = (Student*)malloc(sizeof(Student)); if (studentPtr == NULL) { fprintf(stderr, “Out of memory\n”); exit(1); } *studentPtr = readStudent(); printStudent(*studentPtr); free(studentPtr); } Example 3:

34 main() { Student* class = NULL; int n, i, best = 0; printf(“Enter number of Students: ”); scanf(“%d”, &n); class = (Student*)malloc(n * sizeof(Student)); if (class != NULL) { for (i = 0; i < n; i++) { class[i] = readStudent(); if (class[best].mark < class[i].mark) { best = i; } printf(“Best student: ”); printStudent(class[best]); } free(class); } Example 4:

35 Common Errors Assuming that the size of a structure is the sum of the sizes of its members. Referring to memory already freed. Not freeing memory which is no longer required. Freeing memory not allocated by malloc.

36 #include float** makeMatrix(int n, int m){ float* memoryPtr; float** matrixPtr; int i; memoryPtr = (float*)malloc(n*m*sizeof(float)); matrixPtr = (float**)malloc(n*sizeof(float*)); if (memoryPtr == NULL || matrixPtr == NULL) { fprintf(stderr, “Not enough memory\n”); exit(1); } for (i = 0; i < n; i++, memoryPtr += m){ matrixPtr[i] = memoryPtr; } return matrixPtr; } Example 5:

37Revision sizeof malloc free Common errors. Revision: Reading Kruse 4.5 Deitel and Deitel 12.3 Standish 8.6 King 17 Preparation Next lecture: Nodes and Linked Structures Read Kruse et al. Chapter 4, Section 4.5