Malloc Recitation By sseshadr. Agenda Macros in C Pointer declarations Casting and Pointer Arithmetic Malloc.

Slides:



Advertisements
Similar presentations
Computer Programming Lecture 14 C/C++ Pointers
Advertisements

Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Dynamic memory allocation
An introduction to pointers in c
Pointers. 2 A pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address.
Dynamic Memory Allocation I Topics Basic representation and alignment (mainly for static memory allocation, main concepts carry over to dynamic 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.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
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.
Process, Pointers, and Heap Manager COMPSCI210 Recitation 31 Aug 2012 Vamsi Thummala.
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:
Malloc Recitation Section K (Kevin Su) November 5 th, 2012.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
Lab 3: Malloc Lab. “What do we need to do?”  Due 11/26  One more assignment after this one  Partnering  Non-Honors students may work with one other.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
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.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
Pointers Applications
Computer Organization and Assembly Language C/C++ Pointers and Memory Allocation.
Memory Allocation CS Introduction to Operating Systems.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
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.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Stack and Heap Memory Stack resident variables include:
CS-1030 Dr. Mark L. Hornick 1 Pointers are fun!
Arithmetic Operations. Review function statement input/output comment #include data type variable identifier constant declaration.
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.
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.
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.
Chapter 17 Free-Space Management Chien-Chung Shen CIS, UD
CS 241 Discussion Section (11/17/2011). Outline Review of MP7 MP8 Overview Simple Code Examples (Bad before the Good) Theory behind MP8.
Dynamic Memory Allocation II
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.
CS 241 Discussion Section (2/9/2012). MP2 continued Implement malloc, free, calloc and realloc Reuse free memory – Sequential fit – Segregated fit.
Malloc Lab : Introduction to Computer Systems Recitation 11: Nov. 4, 2013 Marjorie Carlson Recitation A.
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 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
CSE 351 Dynamic Memory Allocation 1. Dynamic Memory Dynamic memory is memory that is “requested” at run- time Solves two fundamental dilemmas: How can.
Carnegie Mellon 1 Malloc Lab : Introduction to Computer Systems Friday, July 10, 2015 Shen Chen Xu.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Carnegie Mellon 1 Malloc Recitation Ben Spinelli Recitation 11: November 9, 2015.
FUNCTIONS (CONT). Midterm questions (21-30) 21. The underscore can be used anywhere in an identifier. 22. The keyword void is a data type in C. 23. Floating.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
APS105 Malloc and 2D Arrays (text Ch6.4, Ch10.2).
Basic Concepts:- Invalid use of Address Operator &75 &(‘a’) &(a+b)
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Variables, Operators, and Expressions
Section 10: Memory Allocation Topics
Dynamic Memory Allocation
CS Introduction to Operating Systems
Lecture 8.
Pointers.
Malloc Lab CSCI 380: Operating Systems
Pointer Arithmetic By Anand George.
Presentation transcript:

Malloc Recitation By sseshadr

Agenda Macros in C Pointer declarations Casting and Pointer Arithmetic Malloc

Macros

Runtime, compile-time, or pre-compile time? Constant: – #define NUM_ENTRIES 100 – OK Macro – #define twice(x) 2*x Not OK twice(x+1) becomes 2*x+1 – #define twice(x) (2*(x)) OK – Use lots of parenthesis, its a naïve search-and-replace!

Macros Why macros? – Faster than function calls Why? – For malloc Quick access to header information (payload size, valid) Whats the keyword inline do? – At compile-time replaces function calls with code

Pointer declarations

C operators (K&R p. 53) OperatorsAssociativity () [] ->.left to right ! ~ * & (type) sizeofright to left * / %left to right + -left to right >left to right >=left to right == !=left to right &left to right ^left to right |left to right &&left to right ||left to right ?:right to left = += -= *= /= %= &= ^= != >=right to left,left to right Note: Unary +, -, and * have higher precedence than binary forms

Review of C Pointer Declarations (K&R section 5.12) int *p int *p[13] int *(p[13]) int **p int (*p)[13] int *f() int (*f)() int (*(*f())[13])() int (*(*x[3])())[5] p is a pointer to int p is an array[13] of pointer to int p is a pointer to a pointer to an int p is a pointer to an array[13] of int f is a function returning a pointer to int f is a pointer to a function returning int f is a function returning ptr to an array[13] of pointers to functions returning int x is an array[3] of pointers to functions returning pointers to array[5] of ints

Pointer casting, arithmetic, and dereferencing

Pointer casting Separate from non-pointer casting – float to int, int to float – to No! gcc error. Cast from – * to * – * to integer/ unsigned int – integer/ unsigned int to *

Pointer casting What actually happens in a pointer cast? – Nothing! Its just an assignment. Remember all pointers are the same size. – The magic happens in dereferencing and arithmetic

Pointer arithmetic The expression ptr + a doesnt always evaluate into the arithmetic sum of the two Consider: * pointer = …; (void *) pointer2 = (void *) (pointer + a); Think about it as – leal (pointer, a, sizeof(type_a)), pointer2;

Pointer arithmetic int * ptr = (int *)0x ; int * ptr2 = ptr + 1; char * ptr = (char *)0x ; char * ptr2 = ptr + 1; int * ptr = (int *)0x ; int * ptr2 = ((int *) (((char *) ptr) + 1)); void * ptr = (char *)0x ; void * ptr2 = ptr + 1; void * ptr = (int *)0x ; void * ptr2 = ptr + 1;

Pointer arithmetic int * ptr = (int *)0x ; int * ptr2 = ptr + 1; //ptr2 is 0x char * ptr = (char *)0x ; char * ptr2 = ptr + 1; //ptr2 is 0x int * ptr = (int *)0x ; int * ptr2 = ((int *) (((char *) ptr) + 1)); //ptr2 is 0x void * ptr = (char *)0x ; void * ptr2 = ptr + 1; //ptr2 is 0x void * ptr = (int *)0x ; void * ptr2 = ptr + 1; //ptr2 is still 0x

More pointer arithmetic int ** ptr = (int **)0x ; int * ptr2 = (int *) (ptr + 1); char ** ptr = (char **)0x ; short * ptr2 = (short *) (ptr + 1); int * ptr = (int *)0x ; void * ptr2 = &ptr + 1; int * ptr = (int *)0x ; void * ptr2 = ((void *) (*ptr + 1)); This is on a 64-bit machine!

More pointer arithmetic int ** ptr = (int **)0x ; int * ptr2 = (int *) (ptr + 1); //ptr2 = 0x c char ** ptr = (char **)0x ; short * ptr2 = (short *) (ptr + 1); //ptr2 = 0x c int * ptr = (int *)0x ; void * ptr2 = &ptr + 1; //ptr2 = ?? //ptr2 is actually 8 bytes higher than the address of the variable ptr int * ptr = (int *)0x ; void * ptr2 = ((void *) (*ptr + 1)); //ptr2 = ?? //ptr2 is just one higher than the value at 0x (so probably segfault)

Pointer dereferencing Basics – It must be a POINTER type (or cast to one) at the time of dereference – Cannot dereference (void *) – The result must get assigned into the right datatype (or cast into it)

Pointer dereferencing What gets returned? int * ptr1 = malloc(100); *ptr1 = 0xdeadbeef; int val1 = *ptr1; int val2 = (int) *((char *) ptr1); What are val1 and val2?

Pointer dereferencing What gets returned? int * ptr1 = malloc(sizeof(int)); *ptr1 = 0xdeadbeef; int val1 = *ptr1; int val2 = (int) *((char *) ptr1); //val1 = 0xdeadbeef; //val2 = 0xffffffef; What happened??

Malloc

Malloc basics What is dynamic memory allocation? Terms you will need to know – malloc/ calloc / realloc – free – sbrk – payload – fragmentation (internal vs. external) – coalescing Bi-directional Immediate vs. Deferred

Fragmentation Internal fragmentation – Result of payload being smaller than block size. – void * m1 = malloc(3); void * m1 = malloc(3); – m1,m2 both have to be aligned to 8 bytes… External fragmentation

Implementation Hurdles How do we know where the chunks are? How do we know how big the chunks are? How do we know which chunks are free? Remember: cant buffer calls to malloc and free… must deal with them real-time. Remember: calls to free only takes a pointer, not a pointer and a size. Solution: Need a data structure to store information on the chunks – Where do I keep this data structure?

The data structure Requirements: – The data structure needs to tell us where the chunks are, how big they are, and whether theyre free – We need to be able to CHANGE the data structure during calls to malloc and free – We need to be able to find the next free chunk that is a good fit for a given payload – We need to be able to quickly mark a chunk as free/allocated – We need to be able to detect when were out of chunks. What do we do when were out of chunks?

The data structure It would be convenient if it worked like: malloc_struct malloc_data_structure; … ptr = malloc(100, &malloc_data_structure); … free(ptr, &malloc_data_structure); … Instead all we have is the memory were giving out. – All of it doesnt have to be payload! We can use some of that for our data structure.

The data structure The data structure IS your memory! A start: – – What goes in the header? Thats your job! – Lets say somebody calls free(p2), how can I coalesce? Maybe you need a footer? Maybe not?

The data structure Common types – Implicit List Root -> chunk1 -> chunk2 -> chunk3 -> … – Explicit List Root -> free chunk 1 -> free chunk 2 -> free chunk 3 -> … – Segregated List Small-malloc root -> free small chunk 1 -> free small chunk 2 -> … Medium-malloc root -> free medium chunk 1 -> … Large-malloc root -> free large chunk1 -> …

Design considerations I found a chunk that fits the necessary payload… should I look for a better fit or not? Splitting a free block: void* ptr = malloc(200); free(ptr); ptr = malloc(50); //use same space, then mark remaining bytes as free void* ptr = malloc(200); free(ptr); ptr = malloc(192);//use same space, then mark remaining bytes as free??

Design Considerations Free blocks: address-ordered or LIFO – Whats the difference? – Pros and cons? Implicit / Explicit / or Seg? – Implicit wont get you very far… too slow. – Explicit is a good place to start, and can be turned into a seg-list. – Seg-list: what are the thresholds?