1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Part IV: Memory Management
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.
Dynamic Memory Management
Dynamic Memory Allocation I Topics Basic representation and alignment (mainly for static memory allocation, main concepts carry over to dynamic memory.
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT.
Prof. Necula CS 164 Lecture 141 Run-time Environments Lecture 8.
User-Level Memory Management in Linux Programming
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
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.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
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
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.
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.
CS 536 Spring Run-time organization Lecture 19.
Run time vs. Compile time
Run-time Environment and Program Organization
1 Inner Workings of Malloc and Free Professor Jennifer Rexford COS 217.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Memory Allocation CS Introduction to Operating Systems.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
Dynamic Memory Allocation Questions answered in this lecture: When is a stack appropriate? When is a heap? What are best-fit, first-fit, worst-fit, and.
CS 403: Programming Languages Lecture 2 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Runtime Environments Compiler Construction Chapter 7.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Compiler Construction
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
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.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 9.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
COMP3190: Principle of Programming Languages
UFS003C3 Lecture 15 Data type in C & C++ Using the STL.
Review 1 List Data Structure List operations List Implementation Array Linked List.
+ 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.
CSC 8505 Compiler Construction Runtime Environments.
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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
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:
CS 326 Programming Languages, Concepts and Implementation
Run-time organization
CSCI206 - Computer Organization & Programming
CSC 253 Lecture 8.
CS Introduction to Operating Systems
CSC 253 Lecture 8.
Dynamic Memory Allocation
Memory Allocation CS 217.
Topic 3-b Run-Time Environment
Lecture 2 SCOPE – Local and Global variables
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation

2 Structure Strings and Arrays Records (structures) Alignment

3 Memory Representation In this diagram, bit 0 is most significant, not least An integer 0x40 0x30 0x20 0x10 occupies the address of The data 1000: : : : 40 The value of 10 is 0(bit 0) 001 (bit 3) 0000

4 Array – memory location by Compiler Int myarray[5] (means from 0 to 4) Since it is int, it occupies 4 bytes If the address is 1000, myarray[0] starts from 1000, myarray[1] from 1004 (note a multiple of 4, not 1) Address *n (where n is myarray[n])

5 Example

6 Array and Pointer The address of myarray[0] is &(myarray[0]) or in visual C++, &myarray (no need to specify [0]) The address of myarray[1] is myarray + 1 (not 4, as it is defined as int), or myarray + N for &myarray[N]

7 Value and relationship – an example int myarray[4] ={101, 102, 103, 104}; &myarray[0] contains 101 or &myarray[1] contains 102 myarray contains 101 The value of myarray[0] is 101 *(int *)(myarray + 0) contains 101 *(int *)(myarray + 1) contains 102 *(int *)(myarray + 2) contains 103

8 String Is an array of character and is terminated by a null character (0x00) char a[4] = “ Hi? ” ; a[0] = H; a[1] = I; a[2] =?; a[3] = 0x00 Incorrect declaration: char char[3] = “Hi?”, as 0x00 is missing

9 Example (1)

10 Example (2)

11 Records (structures) Records store a collection of arbitrary elements that are accessed by name Records are declared using the struct keyword in C or C++ If you group the types (character, integer, double), you can maximize the utilisation It is to group a few structures together.

12 An example struct { char a, b, c, cc; int i; double d; } mystruct; Name is mystruct You can see that it perfectly uses all space.

13 Example – A program

14 Alignment – rearrange the struct struct { char a, b; double d; int i; } mystruct; You can see a few bytes are missing between b and d, in memory it is represented in cccccccc

15 Example

16 Memory Layout and Allocation Several Uses of Memory Heap Allocation Memory Bugs

17 Several uses of Memory Static Allocation (assigned by compiler, such as char a[5] = ‘ 1234 ’ ;) (fixed, you cannot modify during program execution) Dynamic Allocation (requested by program, enter value from your keyboard) Program Memory Layout (memory arrangement for a program)

18 Static Allocation The word static (fix) refers to things that happen at compile time (compile) and link (link) time when the program is constructed. For example, you can define char a[9] = “ ” ; //assign 9 bytes for array a The compiler will assign 9 bytes during compilation Linker will assign the correct address for array a You cannot change it even you think you need 10 bytes while running this program Of course, you can change it by modifying the program and re-compile it

19 Static Allocation vs. C++ static Declarations There is static in C++, but not the same meaning A “ C or C++ ” variable declared as static is allocated statically. For example static bool my_var_initialized = false; static int i = 4; //will remain unchanged We can define variables as global so that it can be accessed by others. Global and static variables have in common that the memory locations are permanent. Local variables are allocated temporarily on a stack.

20 An example int my_var[128]; // a statically allocated variable static bool my_var_initialized = false; //static declaration int my_fn(int x) { if (my_var_initialized) return; my_var_initialized = true; for (int i = 0; i < 128; i++) my_var[i] = 0; } Initially, it is false

21 int my_var[128]; // a statically allocated variable int my_fn(int x) { // note that the initialization of my_var_initialized // takes place only once, not every time my_fn() is called: static bool my_var_initialized = false; if (my_var_initialized) return; my_var_initialized = true; for (int i = 0; i < 128; i++) my_var[i] = 0; } Explanation to previous example

22 Dynamic allocation Limitations of Static Allocation If two procedures use a local variable named i, there will be a conflict if both i's are globally visible. If i is only declared once, then i will be shared by the two procedures. One might call the other, even indirectly, and cause i to be overwritten unexpectedly. It would be better if each procedure could have its own copy of i.

23 Limitations of static allocation programs do not always know how much storage is required until run time, so static allocation is inaccurate. For example, you allocated 5 bytes, but later you find that you need 6 bytes. static allocation reserves memory for the duration of the program, but often a data structure is only needed temporarily

24 Stack Allocation It is the most common form of dynamic allocation. It is a standard feature of modern programming languages, including C and C++, as stacks support recursion and dynamic allocation. When a function is called, memory is allocated on the stack to hold parameter values, local variables, and the address of the calling function

25 Grab memory To grab memory, we have to use malloc(size). For example ptr = malloc(4) will return a pointer with memory size of 4 bytes ptr = malloc(4*int) will return a pointer with 16 bytes = 4 x 4 (integer) = 16 bytes malloc(4*long) will return a pointer with 16 bytes = 4 x 4 (long) = 16 bytes free(ptr), free this pointer to the memory

26 Program Interfaces - two void *malloc(size_t size); Allocates a block of memory of size Size_t : type Size: the actual size 1. Example ptr = (int *)malloc(512); //allocate 512*4 ptr= (char *)malloc(512);// allocate 512 bytes ptr = (short *)malloc(512*sizeof(short)); //allocate 512*2 2. void free(void *ptr); //return the pointer Example: free(ptr);

27 Example

28 Activation Record - Example – foo()- >bar()->baz(), determine the return address int foo() { int b; b = bar(); return b; } int bar() { int b = 0; b = baz(b); return b; } int baz(int b) { if (b < 1) return baz(b + 1); else return b; }

29 Activation record When a function / subroutine is called, it will create an activation record. This record contains the location of local variable, return address etc.

30 An example – bar()

31 Example of a simple program

32 An example – return address

33 Returning From a Function Call Function returns are almost identical to function calls, except that everything runs in reverse. Before a function returns, it loads a particular register with the computed return value.

34 Difficulties of memory allocation malloc() will have to allocate the memory that has been used before. There must be a method to determine which memory blocks can be used. They are: First free(or first fit) (the first block in the list that meets the requirement ) Best fit (the block that perfectly meets the requirements Worst fit( the largest one in the list)

35 Fragmentation – means holes Although it has memory

36 Example of First fit

37 Example of Best fit

38 Example of Worst fit

39 External Fragmentation Fragmentation is undesirable because it means that memory is used inefficiently. A program tries to call operating system to get memory but it does not return even there are blocks of memory. It is because: The blocks of memory are are too small. It causes external fragmentation. For example, I need 12K. There are two 10Ks, but none of them fits me. 10K

40 Simple Algorithms Block Sizes Finding Free Blocks Splitting a Free Block Finding a Suitable Block Coalescing Free Blocks (combine) Searching for Free Blocks No need to memorise, very difficult to understand

41 Simple Algorithms (1) 1. How do you find free blocks from which to allocate? 2. How do you select a free block to allocate? Pick the first one or best one? 3. If you need fewer bytes than you find in a free block, should you split the block or use the whole?

42 Simple Algorithms (2) 1. Only a pointer is passed to free(). How do you know how many bytes are in the block? 2. When a block is freed, should you join it to neighboring free blocks (if any) to make a larger one? If so, how do you find neighboring blocks?

43 Summary (1) Structure: group a few declarations together Record: group structures Static allocation (char[8]) and dynamic memory (malloc()) Static declaration, like global variable (static int i) Stack memory – a temporary memory for subroutine

44 Summary (2) Heap: is a large block of data, char a[513] Malloc(sie_t size) to return a pointer pointing to the memory block Free(ptr), remember to free memory Fragmentation: memory is available but is not continuous for use