Class 2 CSI2172

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

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.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Chapter 6 Data Types
Programming Languages and Paradigms The C Programming Language.
Class 3 CSI2172
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
1 Memory Allocation Professor Jennifer Rexford COS 217.
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.
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.
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:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
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.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Pointers. 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.
CSSE 332 Explicit Memory Allocation, Parameter passing, and GDB.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
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.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Lecture 13 Static vs Dynamic Memory Allocation
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
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,
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
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.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
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.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
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.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
+ 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.
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.
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.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Dynamic Allocation in C
Memory allocation & parameter passing
Stack and Heap Memory Stack resident variables include:
Day 03 Introduction to C.
Introduction to Programming
Day 03 Introduction to C.
CSCI206 - Computer Organization & Programming
Arrays & Dynamic Memory Allocation
Pointers, Dynamic Data, and Reference Types
Memory Allocation CS 217.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory.
C Programming Lecture-8 Pointers and Memory Management
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Class 2 CSI2172

Into C++: Data Structure: Class (start) Syntax: class { … }; class TwoTurtledoves{ public: method ( ){ method body } };

example review Topcoder Problem (copyright, used in educational context) SRM224 Div 1 I give my true love presents every day. On day 1, I give her one Type 1 present. On day 2, I give her two Type 2 presents, followed by one Type 1 present. On day 3, I give her three Type 3 presents, followed by two Type 2 presents, followed by one Type 1 present. This pattern continues day after day. Soon I begin to wonder, what type of present will be the 100th present that I give my true love? The 1000th? The th? For example, the 10th present that I give my true love is the Type 1 present on day 3. Write a method that takes an int n and returns the type of the nth present that I give my true love. Note that n is one-based, so n=1 refers to the very first present I give her (the Type 1 present on day 1).

example problem review Solving by questions: Q1: How many gifts do I give on day d ? int Q1(int d){ GiftNum = 0; for(int i=1; i<=d; i++ ){ GiftNum +=i; } return GiftNum; };

example problem review Solving by questions: Q2: How many gifts will I have given by day d (d included) int Q2(int d){ int GiftNum = 0; for(int i=1; i<=d; i++ ){ GiftNum += Q1(i); } return GiftNum; };

example problem review Solving by questions: Q3: On which day will I be giving the nth present to my true love ? (d) int Q3(int n){ int Day = 1; while(Q2(Day) < n) Day++; return Day; };

example problem review Solving by questions: Q4: If I’m giving gift number g of day d, what is the type of gift number g ? int Q4(int i, int day){ int Type = day; int numGifts = 0; while( numGifts + Type < i){ numGifts += Type; Type--; } return Type; };

pointeurs  A variable that contains as its value the address of another variable 0X0A2BB 0X0A2B9 0X0A2BA 0X0A2B8 0X0A2BC 0X0A2BD 0X0A2BE … int* ptr; Not defined yet (garbage) int* ptr; int a; int* ptr; int a; ptr = &a; 0X0A2BD ptr is now initialized int* ptr; int a; ptr = &a; a = 123; 123 ptr a

0X0A2BB 0X0A2B9 0X0A2BA 0X0A2B8 0X0A2BC 0X0A2BD 0X0A2BE … 0X0A2BD 123 ptr a &a ptr &ptr *ptr a == 0x0A2BD == 0x0A2B8 == 123

Pointeurs are also types Pointeurs are also typed There is a generic void* int a; char c; int* pi; char* pc; void* gp; pi = &a; /* OK */ pi = &c; /* TYPE MISMATCH */ pc = &c; /* OK */ pc = &a; /* TYPE MISMATCH */ gp = &a; /* OK */ gp = &c; /* OK */

Allocating memory: Memory: 3 Static: Memory is allocated by the linker at the beginning of the program’s execution. The memory is deallocated at execution’s end. 3 Automatic: The memory is automatically allocated, managed and deallocated during the program’s execution. Function arguments and local variables get automatic memory. 3 Dynamic: Memory is requested explicitly by the programmer. The programmer manages and deallocates the memory.

Find the variable compile-time program-text i global variables i static variables automatic stack i local variables i function parameters i return values of functions run-time heap i malloc i new

Automatic and static memory are easy int x; /* global */ int f(int n) { int x; /* local to f */ if (n > 3) { int x; /* local to if */... } { /* a local scope * "out of the blue" */ int x; } S T A T I C Constants Global Variables Variables declared as: static A U T O M A T I C Local Variables Function parameters Function return

Dynamic memory C Is harder. You have to be careful. This is where your main source of run time errors will be. C What does a run time error look like ? C The heap stores dynamically allocated memory blocks. C There are data structures that thrive on dynamic memory C what’s a tree ? C What’s a list ? C In C++ (unlike java), there is no garbage collector

int * x = (int*)malloc(sizeof(int)); int * a = (int*)calloc(10,sizeof(int)); *x = 3; a[2] = 5; free(a); a = 0; free(x); x = 0; (C) void* malloc(size_t size); void* calloc(size_t n, size_t size); void* realloc(void * ptr,size_t size); void free(void * ptr);

Request for memory allocation ( malloc ) † malloc requests the allocation of a memory block of size bytes on the heap. † Syntaxe : #include void *malloc(size_t size); † Returned Value : This is a function call. On success, it returns a pointer to the newly allocated memory. On failure (not enough memory or bad argument), malloc returns NULL. † Careful : dynamic memory functions return void* types. You have to cast the return value in order to use it. #include main() { char *ptr; struct s_fiche { char nom[30]; int numero; struct s_fiche *suiv; } *fiche; ptr = (char *) malloc(80); // 80 bytes request if ( ptr == NULL) {printf(“didn’t work\n"); exit(1);} if (fiche = (struct s_fiche *) malloc(sizeof(struct s_fiche)) == NULL) {printf(" didn’t work\n "); exit(1);} free(fiche); /* dealocate */ free(ptr); }

The C++ equivalent is ( new ) † new is not a function call. It is an operator. There are subtle differences. new allocates memory for an object or array of objects and returns a suitably typed, nonzero pointer to the object. int main(){ //Use new operator to allocate // an array of 20 characters. char *AnArray = new char[20]; for( int i = 0; i < 20; ++i ){ // On the first iteration of the loop, allocate // another array of 20 characters. if( i == 0 ){ char *AnotherArray = new char[20]; } delete AnotherArray; // Error: pointer out of scope. delete AnArray; // OK: pointer still in scope. }

2 dimensions (matrix): double ** alloc_matrix(int n, int m) { double ** M = new double* [n]; int i; for(i=0; i<n; ++i) M[i] = new double [m]; return M; }