. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Dynamic Memory Management
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Chapter 7: User-Defined Functions II
1 Memory Allocation Professor Jennifer Rexford COS 217.
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:
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
. Virtual Classes & Polymorphism. Example (revisited) u We want to implement a graphics system u We plan to have lists of shape. Each shape should be.
Informática II Prof. Dr. Gustavo Patiño MJ
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
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 Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Run-Time Storage Organization
Run time vs. Compile time
Lecture 3 Interfaces Pointers to Functions Memory bugs, File I/O Variables – the special kind.
Run-time Environment and Program Organization
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.
Memory Layout C and Data Structures Baojian Hua
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
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
Runtime Environments Compiler Construction Chapter 7.
1 MT258 Computer Programming and Problem Solving Unit 7.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
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,
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.
1 Writing a Good Program 8. Elementary Data Structure.
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.
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.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CSCI Rational Purify 1 Rational Purify Overview Michel Izygon - Jim Helm.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
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.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Multiple file project management & Makefile
Memory Management.
Dynamic Allocation in C
Chapter 7: User-Defined Functions II
Dynamic Memory Allocation
Checking Memory Management
Dynamic Memory Allocation
Pointers, Dynamic Data, and Reference Types
Dynamic Memory Allocation
Memory Allocation CS 217.
Binding Times Binding is an association between two things Examples:
RUN-TIME STORAGE Chuen-Liang Chen Department of Computer Science
Pointers, Dynamic Data, and Reference Types
Module 13 Dynamic Memory.
Presentation transcript:

. Memory Management

Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap

Stack u Maintains memory during function calls  Argument of the function  Local variables  Call Frame u Variables on the stack have limited “life time”

Stack - Example int foo( int a, double f ) { int b; … } a f b

Stack - Example int foo( int a, double f ) { int b; … { int c; … } … } a f b

Stack - Example int foo( int a, double f ) { int b; … { int c; … } … } a f b c

Stack - Example int foo( int a, double f ) { int b; … { int c; … } … } a f b c

Stack - Example int foo( int a, double f ) { int b; … { int c; … } … } a f b c

Stack – recursive example void foo( int depth ) { int a; if( depth > 1 ) foo( depth-1 ); } int main() { foo(3); … depth a depth a depth a

Stack -- errors void foo( int depth ) { int a; if( depth > 1 ) foo( depth ); } Will result in run time error: out of stack space

Static heap u Memory for global variables #include const int ListOfNumbersSize = 1000; int ListOfNumbers[ListOfNumbersSize]; int main() { …

Static heap u Variables on the static heap are defined throughout the execution of the program u Memory on the static heap must be defined at compile time

Static heap: reverse example Example: program to reverse the order of lines of a file To this task, we need to u read the lines into memory u Print lines in reverse How do we store the lines in memory?

Static heap: reverse example const int LineLength = 100; const int NumberOfLines = 10000; char Lines[NumberOfLines][LineLength]; … int main() { int n = ReadLines(); for( n-- ; n >= 0; n-- ) printf(“%s\n”, Lines[n]); }

Static heap: reverse example This solution is problematic: u The program cannot handle files larger than these specified by the compile time choices  If we set NumberOfLines to be very large, then the program requires this amount of memory even if we are reversing a short file  Want to use memory on “as needed” basis

Dynamic Heap u Memory that can be allocated and freed by the program during run time u The program controls how much is allocated and when u Limitations based on run-time situation  Available memory on the computer

Allocating Memory from Heap void *malloc( size_t Size );  Returns a pointer to a new memory block of size Size  Returns NULL if it cannot allocate memory of this size

Example: strdup Function to duplicate a string: char * strdup( char const *p ) { int n = strlen(p); char* q =(char*)malloc(sizeof(char)*(n+1)); if( q != NULL ) strcpy( q, p ); return q; } This function is part of the standard library

Memory Management void foo( char const* p ) { char *q = strdup( p ); // do something with q } The allocated memory remains in use u cannot be reused later on p q … Heap ‘a’ ‘b’ ‘\0’

De-allocating memory void free( void *p );  Returns the memory block pointed by p to the pool of unused memory u No error checking!  If p was not allocated by malloc, undefined behavior

Example of free void foo( char const* p ) { char *q = strdup( p ); // do something with q free(q); } This version frees the allocated memory

Further Knowledge Read manual page of u malloc u calloc u free

Interfaces u A definition of a set of functions that provide a coherent module (or library)  Data structure (e.g., list, binary tree)  User interface (e.g., drawing graphics)  Communication (e.g., device driver)

Interface - modularity u Hide the details of implementing the module from its usage  Specification – “what”  Implementation – “how”

Interface – information hiding u Hide “private” information from outside  The “outside” program should not be able to use internal variables of the module  Crucial for modularity u Resource management  Define who controls allocation of memory

Example interface - StrStack u A module that allows to maintain a stack of strings u Operations:  Create new  Push string  Pop string  IsEmpty [See attached StrStack.h]

Implementation of StrStack Decision #1: data structure u Linked list u Array (static? dynamic?) u Linked list of arrays u … We choose linked list for simplicity

Implementation of StrStack Decision #2: Resource allocation u Duplicated strings on stack or keep pointer to original? u If duplicate, who is responsible for freeing them? We choose not to duplicate --- leave this choice to user of module

Implementation of StrStack u See StrStack.c

Using StrStack int main() { char *Line; StrStack *Stack = StrStackNew(); while( (Line = ReadLine()) != NULL ) StrStackPush( Stack, Line ); while( (Line = StrStackPop(Stack)) != NULL ) { printf("%s\n", Line ); free( Line ); } return 0; }

Interface Principles Hide implementation details u Hide data structures u Don’t provide access to data structures that might be changed in alternative implementation u A “visible” detail cannot be later changed without changing code using the interface!

Interface Principles Use small set of “primitive” actions u Provide to maximize functionality with minimal set of operations u Do not provide unneeded functions “just because you can”

Interface Principles Don’t reach behind the back u Do not use global variables or unexpected side effects u Do not assume specific order of operations by the user  Such assumptions suggest the set of primitives is wrong

Interface Principle Consistent Mechanisms u Do similar things in a similar way  strcpy(dest, source)  memcpy(dest, source)

Interface Principle Resource Management u Free resource at the same level it was allocated u Assumptions about resources

Debugging “Define” the bug --- reproduce it 2. Use debugger 3. Don’t panic --- think! 4. Divide & Conquer