6-1 Embedded Systems C Programming Language Review and Dissection IV Lecture 6.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Memory Management Chapter FourteenModern Programming Languages, 2nd ed.1.
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.
Dynamic memory allocation
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.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
User-Level Memory Management in Linux Programming
ספטמבר 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.
1 C Review and Dissection V: Dynamic Memory Allocation and Linked Lists These lecture notes created by Dr. Alex Dean, NCSU.
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.
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:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Memory Management Memory Areas and their use Memory Manager Tasks:
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 Inner Workings of Malloc and Free Professor Jennifer Rexford COS 217.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Pointers Applications
Memory Allocation CS Introduction to Operating Systems.
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.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
Pointers OVERVIEW.
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.
Chapter 17 Free-Space Management Chien-Chung Shen CIS, UD
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.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
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.
CSE 351 Dynamic Memory Allocation 1. Dynamic Memory Dynamic memory is memory that is “requested” at run- time Solves two fundamental dilemmas: How can.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
1 Compiler Construction Run-time Environments,. 2 Run-Time Environments (Chapter 7) Continued: Access to No-local Names.
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.
Dynamic Allocation in C
Chapter 17 Free-Space Management
Stack and Heap Memory Stack resident variables include:
Dynamic Allocation Review Structure and list processing
ENEE150 Discussion 07 Section 0101 Adam Wang.
C Programming Language Review and Dissection IV
Circular Buffers, Linked Lists
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
Topic 3-b Run-Time Environment
Dynamic Memory A whole heap of fun….
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Dynamic Memory A whole heap of fun….
Chapter 10-1: Dynamic Memory Allocation
Comp 208 Computers in Engineering Yi Lin Fall, 2005
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Dynamic Data Structures
Presentation transcript:

6-1 Embedded Systems C Programming Language Review and Dissection IV Lecture 6

Embedded Systems6-2 Today Dynamic Memory Allocation Linked Lists

Embedded Systems6-3 Dynamic Memory Allocation Why How it’s used in C Example with linked lists Dangers

Embedded Systems6-4 Dynamic Memory Management In addition to storing variables in global data section and run- time stack, we can dynamically allocate memory from a heap of free space (Patt & Patel 19.4) Allows more flexible programming –Can allocate memory as needed, deallocate when done Function interfaces in stdlib.h (C Standard Library) instructions 0xFFFFF 0x00000 PC global data SP FB heap run-time stack

Embedded Systems6-5 Dynamic Memory Allocation in C Why? –Some systems have changing memory requirements, and stack variables (automatic) aren’t adequate –Example: Voice recorder needs to store recordings of different lengths. Allocating the same size buffer for each is inefficient How? –Allocate nbytes of memory and return a start pointer void * malloc (size_t nbytes); –Allocate nelements*size bytes of memory and return a start pointer void * calloc (size_t nelements, size_t size); –Change the size of a block of already-allocated memory void * realloc (void * pointer, size_t size); –Free a block of allocated memory void free (void * pointer);

Embedded Systems6-6 Using Dynamic Memory Management Request space for one or more new variables –Request pointer to space for one element int * j, *k; j = (int *) malloc (sizeof(int)); *j = 37; –Request pointer to space for array of elements and initialize to zero k = (int *) calloc(num_elements, sizeof(int)); k[0] = 55; k[1] = 31; –These return NULL if there isn’t enough space Program has to deal with failure -- embedded program probably shouldn’t just quit or reset…. Free up space when done using variables free(k);

Embedded Systems6-7 Example Application: Voice Recorder Recording –While record switch is pressed sample microphone store in temporary RAM buffer –When record switch is released copy audio to a permanent buffer add to end of list of recordings Playback and skipping –forward switch: skip forward over one recording, wrap around at end –play switch: play the current recording –delete switch: delete the current recording Data Structure: linked list of recordings buffer recordings record delete

Embedded Systems6-8 Data Structure Detail: Linked List Each list element is defined as a structure with fields –AudioSize: Number of bytes –AudioData: … –Next: Pointer to next list element typedef struct { unsigned AudioSize; char * AudioData; struct List_T * Next; } List_T;

Embedded Systems6-9 Code for Voice Recorder main unsigned char buffer[MAX_BUFFER_SIZE]; struct List_T * recordings = NULL, * cur_recording = NULL; void main(void) { while (1) { while (NO_SWITCHES_PRESSED) ; if (RECORD) handle_record(); else if (PLAY) handle_play(); else if (FORWARD) handle_forward(); else if (DELETE) handle_delete(); }

Embedded Systems6-10 Code for handle_forward void handle_forward(void) { if (cur_recording) cur_recording = cur_recording->Next; if (!cur_recording) cur_recording = recordings; }

Embedded Systems6-11 Code for handle_record void handle_record(void) { unsigned i, size; unsigned char * new_recording; struct List_T * new_list_entry; i = 0; while (RECORD) buffer[i++] = sample_audio(); size = i; new_recording = (unsigned char *) malloc (size); for (i=0; i<size; i++) /* could also use memcpy() */ new_recording[i] = buffer[i]; new_list_entry = (List_T *) malloc ( sizeof(List_T) ); new_list_entry->AudioData = new_recording; new_list_entry->AudioSize = size; new_list_entry->Next = NULL; recordings = Append(recordings, new_list_entry); }

Embedded Systems6-12 Code for handle_delete void handle_delete(void) { List_T * cur = recordings; if (cur == cur_recording) recordings = recordings->Next; else { while (cur->Next != cur_recording) cur = cur->Next; /* cur now points to previous list entry */ cur->Next = cur_recording->Next; } free(cur_recording->AudioData); free(cur_recording); }

Embedded Systems6-13 Allocation Data Structures Keep free memory in sorted list of free blocks typedef struct hdr { struct hdr * next; unsigned int size; }; hdr * FreeList; Assume hdr takes no space for examples More details in “ Memory Allocation in C, ” Leslie Alridge, Embedded Systems Programming, August 1989 Used Size = 412 Next Size = 508 Next Size = 38 Next Size = 88 Next FreeList

Embedded Systems6-14 Allocation Operations To allocate memory –find first block of size >= requested_size –modify list to indicate space isn’t free if sizes match exactly, remove free block from list else split memory –reduce size field by requested_size, keeping first part of block in free space –allocate memory in second part of block return pointer to newly allocated block To free memory depends on block’s memory location –If before first free block, prepend it at head of free list –If between free list entries, insert in list –If after last free block, append it at tail of free list Freed memory block may be adjacent to other free blocks. If so, merge contiguous blocks

Embedded Systems6-15 Dangers of Dynamic Memory Allocation Memory leaks waste memory –Never freeing blocks which are no longer needed. User’s responsibility. May accidentally use freed memory –User’s responsibility. Allocation speed varies –Linked list must be searched for a block which is large enough –Bad for a real-time system, as worst case may be large. Fragmentation –Over time free memory is likely to be broken into smaller and smaller fragments. –Eventually there won’t be a block large enough for an allocation request, even though there is enough total memory free

Embedded Systems6-16 Heap and Fragmentation Problem: –malloc/calloc/free use a heap of memory; essentially a list of blocks of empty and used memory –Repeated allocation/free cycles with differently sized allocation units leads to fragmentation Although there may be enough memory free, it may be fragmented into pieces too small to meet request Solutions (none optimal): –Always allocate a fixed size memory element –Use multiple heaps, each with a fixed element size