Malloc Recitation Section K (Kevin Su) November 5 th, 2012.

Slides:



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

An introduction to pointers in c
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
Process, Pointers, and Heap Manager COMPSCI210 Recitation 31 Aug 2012 Vamsi Thummala.
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.
Week 7 - Friday.  What did we talk about last time?  Allocating 2D arrays.
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:
Binghamton University CS-220 Spring 2015 Binghamton University CS-220 Spring 2015 Heap Management.
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.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
1 Optimizing Malloc and Free Professor Jennifer Rexford
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
1 Inner Workings of Malloc and Free Professor Jennifer Rexford COS 217.
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.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
L6: Malloc Lab Writing a Dynamic Storage Allocator October 30, 2006
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.
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
7. Pointers, Dynamic Memory 20 th September IIT Kanpur 1C Course, Programming club, Fall 2008.
Stack and Heap Memory Stack resident variables include:
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #6C Pointers,
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.
1 Dynamic Memory Allocation: Basic Concepts. 2 Today Basic concepts Implicit free lists.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
November 18, 2015Memory and Pointers in Assembly1 What does this C code do? int foo(char *s) { int L = 0; while (*s++) { ++L; } return L; }
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
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. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Carnegie Mellon Dynamic Memory Allocation : Introduction to Computer Systems Monday March 30th,
Consider Starting with 160 k of memory do: Starting with 160 k of memory do: Allocate p1 (50 k) Allocate p1 (50 k) Allocate p2 (30 k) Allocate p2 (30 k)
Dynamic Memory Allocation II
Carnegie Mellon 1 Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition Dynamic Memory Allocation: Basic Concepts :
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.
CS 241 Discussion Section (12/1/2011). Tradeoffs When do you: – Expand Increase total memory usage – Split Make smaller chunks (avoid internal fragmentation)
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.
University of Washington Implementation Issues How do we know how much memory to free given just a pointer? How do we keep track of the free blocks? How.
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.
Carnegie Mellon Dynamic Memory Allocation : Introduction to Computer Systems Recitation 11: Monday, Nov 3, 2014 SHAILIN DESAI SECTION L 1.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Memory Management What if pgm mem > main mem ?. Memory Management What if pgm mem > main mem ? Overlays – program controlled.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Section 10: Memory Allocation Topics
ENEE150 Discussion 07 Section 0101 Adam Wang.
Dynamic Memory Allocation
CSCI206 - Computer Organization & Programming
The Hardware/Software Interface CSE351 Winter 2013
Optimizing Malloc and Free
CS Introduction to Operating Systems
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Memory Allocation II CSE 351 Autumn 2017
Memory Allocation II CSE 351 Winter 2018
Memory Allocation II CSE 351 Winter 2018
7. Pointers, Dynamic Memory
Malloc Lab CSCI 380: Operating Systems
Pointer Arithmetic By Anand George.
Week 7 - Friday CS222.
Presentation transcript:

Malloc Recitation Section K (Kevin Su) November 5 th, 2012

Agenda Macros / Inline functions Quick pointer review Malloc

Macros / Inline Functions

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, it’s a naïve search-and-replace!

Macros Why macros? “Faster” than function calls Why? For malloc Quick access to header information (payload size, valid)

Inline Functions What’s the keyword inline do? At compile-time replaces “function calls” with code More efficient than a normal function call Overhead – no need to set up stack/function call Useful for functions that are Called frequently Small, i.e. int add(int x, int y);

Differences Macros done at pre-compile time Inline functions done at compile time Stronger type checking / Argument consistency Macros cannot return anything (why not?) Macros can have unintended side effects #define xsquared(x) (x*x) What happens when xsquared(x++) is called? Hard to debug macros – errors generated on expanded code, not code that you typed

Macros / Inline Functions You will likely use both in malloc lab Macros are good for small tasks Saves work in retyping tedious calculations Can make code easier to understand HEADER(ptr) versus doing the pointer arithmetic Some things are hard to code in macros, so this is where inline functions come into play More efficient than normal function call More expressive than macros

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! It’s just an assignment. Remember all pointers are the same size. The magic happens in dereferencing and arithmetic

Pointer arithmetic The expression ptr + a doesn’t 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: can’t 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 they’re 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 we’re out of chunks. What do we do when we’re 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 we’re giving out. All of it doesn’t 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? That’s 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 -> …

Implicit List From the root, can traverse across blocks using headers Can find a free block this way Can take a while to find a free block How would you know when you have to call sbrk?

Explicit List Improvement over implicit list From a root, keep track of all free blocks in a (doubly) linked list Remember a doubly linked list has pointers to next and previous When malloc is called, can now find a free block quickly What happens if the list is a bunch of small free blocks but we want a really big one? How can we speed this up?

Segregated List An optimization for explicit lists Can be thought of as multiple explicit lists What should we group by? Grouped by size – let’s us quickly find a block of the size we want What size/number of buckets should we use? This is up to you to decide

Design Considerations I found a chunk that fits the necessary payload… should I look for a better fit or not? (First fit vs. Best fit) 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 What’s the difference? Pros and cons? Coalescing When do you coalesce? Probably should use explicit or a seg list