CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

Similar documents
CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Dynamic Data Structures. CSCI 112: Programming in C

Lecture 8 Dynamic Memory Allocation

C Programming Basics II

Dynamic Allocation in C

CS Programming In C

Dynamic Allocation in C

CS 610: Intermediate Programming: C/C++ Making Programs General An Introduction to Linked Lists

In Java we have the keyword null, which is the value of an uninitialized reference type

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Memory Management. CSC215 Lecture

Dynamic Memory. R. Inkulu (Dynamic Memory) 1 / 19

C Structures & Dynamic Memory Management

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Programs in memory. The layout of memory is roughly:

Arrays and Pointers (part 1)

by Pearson Education, Inc. All Rights Reserved.

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Understanding Pointers

ECE551 Midterm Version 1

ECE 2400 Computer Systems Programming Fall 2018 Topic 6: C Dynamic Allocation

Dynamic Memory Allocation

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Computer Programming: Skills & Concepts (CP) Strings

ECE551 Midterm Version 2

Fall 2018 Discussion 2: September 3, 2018

Dynamic memory. EECS 211 Winter 2019

Memory Management in C (Dynamic Strings) Personal Software Engineering

Intermediate Programming, Spring 2017*

ECE551 Midterm Version 1

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

DAY 3. CS3600, Northeastern University. Alan Mislove

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Contents of Lecture 3

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Kurt Schmidt. October 30, 2018

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Memory Allocation. General Questions

o Code, executable, and process o Main memory vs. virtual memory

Memory, Arrays & Pointers

Arrays and Memory Management

Arrays and Pointers (part 1)

ECE 551D Spring 2018 Midterm Exam

Dynamic Memory & ADTs in C. The heap. Readings: CP:AMA 17.1, 17.2, 17.3, The primary goal of this section is to be able to use dynamic memory.

Dynamic Memory & ADTs in C

Memory (Stack and Heap)

Advanced Pointer Topics

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Binghamton University. CS-211 Fall Dynamic Memory

CP2 Revision. theme: dynamic datatypes & data structures

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

CS201 Some Important Definitions

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Memory. Memory Topics. Passing by Value. Passing by Reference. Dynamic Memory Allocation. Passing a Pointer to a Pointer. Related Memory Functions

Lecture 05 Pointers ctd..

Memory Management I. two kinds of memory: stack and heap

Heap Arrays. Steven R. Bagley

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CS 222: Pointers and Manual Memory Management

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0)

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

CSC 1600 Memory Layout for Unix Processes"

CS 11 C track: lecture 5

CS201- Introduction to Programming Current Quizzes

Arrays, Pointers and Memory Management

Lecture 3 Memory and Pointers

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CS 322 Operating Systems Practice Midterm Questions

Memory Organization. The machine code and data associated with it are in the code segment

Reminder: compiling & linking

ECE 551D Spring 2018 Midterm Exam

The C++ Object Lifecycle. EECS 211 Winter 2019

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Object-Oriented Principles and Practice / C++

edunepal_info

CS 241 Data Organization Binary Trees

Arrays, Strings, and Pointers

Heap Arrays and Linked Lists. Steven R. Bagley

Cpt S 122 Data Structures. Data Structures

CS24 Week 2 Lecture 1

Lecture 3 Memory and Pointers

14. Memory API. Operating System: Three Easy Pieces

CS 107 Lecture 5: Arrays. and Pointers in C. Monday, January 22, Stanford University. Computer Science Department

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Lectures 13 & 14. memory management

Dynamic memory allocation (malloc)

Short Notes of CS201

CS61C : Machine Structures

CPSC 427: Object-Oriented Programming

Transcription:

... 1/30 CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation Alice E. Fischer October 23, 2015

... 2/30 Outline Storage Class Dynamic Allocation in C Dynamic Allocation in C++ Using Dynamic Arrays FlexArrays in C An Application of FlexArrays Low-level Memory Operations

... 3/30 Storage Class Storage Class

... 4/30 Storage Class Storage Class Keyword auto static extern Meaning The default. Used for parameters and local variables. Allocated by every function call and deallocated by every function return. This implements a block-structured memory. For variables that must not come and go every time a function is called or returns. Unusual but important. Used in large complex programs to let code from one module use a variable in a different module. Dynamic storage is used when an object must outlast the block that created it.

... 5/30 Storage Class Your Address Space This is the classic model for four kinds of memory management sharing one user s address space. Laid out at compile time. Created & initialized at load time Objects are created by malloc or calloc and recycled by free Your executable code and literals. Read only Static variables heap: Dynamic allocation A stack frame is created by each function call and deleted by each function return run-time stack: parameters and local variables

... 6/30 Dynamic Allocation in C Dynamic Allocation in C malloc(): memory allocation calloc(): cleared memory allocation realloc(): resize an allocated area (larger or smaller) free(): recycle the allocation

... 7/30 Dynamic Allocation in C Allocation Functions - malloc() and calloc() These functions and size_t are defined in (standard library) stdlib.h void* malloc( size_t sz ); Mass memory allocation. Return a pointer to an uninitialized block of dynamic memory that is sz bytes long. void* calloc ( size_t n, size_t sz ); Cleared memory allocation. Allocate a dynamic array of n objects each of size sz bytes. Initialize all bits to 0. Return a pointer to the first byte of the array.

... 8/30 Dynamic Allocation in C Results of malloc() and calloc() The shaded space is allocated by the system for its own use. It is initialized to the number of bytes in the allocated area. p int* p = malloc( 10* sizeof(int)); 44?????????? q int* q = calloc( 4, sizeof(double)); 36 0.0 0.0 0.0 0.0

... 9/30 Dynamic Allocation in C Declaration and Initialization An array of arrays is declared with two subscripts and initialized by a series of array initializers: short multtable[4][4] = { {1, 2, 3, 4 }, {2, 4, 6, 8 }, {3, 6, 9, 12}, {4, 8, 12,16} } ; multtable [0] [1] [2] [3] [0] [1] [2] [3] 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 To refer to an array slot, the row subscript is given first: multtable[2][3] is 12.

... 10/30 Dynamic Allocation in C Example: Using dynamic memory for strings. When we use strings in our data structures, we often use dynamic allocation to get an array that is exactly the right size for each input string we get. Read the string into a buffer that is long enough for the longest expected input. If the buffer is 81 chars, read the string using " %80[^\n]" Use strlen to measure the string: len = strlen( buffer ); Allocate space for the string and a terminator: char* name = malloc( (len+1) * sizeof(char) ); Copy the data into the new memory: strcpy( name, buffer );

... 11/30 Dynamic Allocation in C Dynamic String Allocation buffer Margaret Thatcher\0 name Margaret Thatcher\0 Allocated on the run-time stack Allocated in the dynamic heap

... 12/30 Dynamic Allocation in C Allocation Functions - free() void free( void* pt ); Recycle a memory block. This function works on a memory block that was previously allocated by malloc() or calloc(). It returns the block of memory starting at pt, to the operating system for eventual reuse. A block should be freed after it no longer is needed by the program. It must not be accessed after the call to free().

... 13/30 Dynamic Allocation in C Allocation Functions - realloc() void* realloc( void* pt, size_t sz ); Mass memory reallocation or resizing. This function works on a memory block that was previously allocated by malloc() or calloc(). Given a new number of bytes, sz, that is different from the current size of pt s block, resize the block to the new length. If the new length is longer, and if adjacent storage is available, simply extend the block size. If the old block cannot be extended, allocate a new big-enough block elsewhere and copy the entire contents of the old block to the new one. Free the old block.

... 14/30 Dynamic Allocation in C Operation of realloc p max = 4 p = malloc (max * sizeof(int) ); 20???? Later, when the array is full and more data must be stored: p max *= 2; p = realloc (p, max * sizeof(int) ); 36 3 17 8 41???? The reallocated array may be at the same memory address as the original, or it may be located somewhere else. in memory.

... 15/30 Dynamic Allocation in C++ Dynamic Allocation in C++ new new[] delete delete[]

... 16/30 Dynamic Allocation in C++ Allocation Operator - new This operator is part of the core language. Basic syntax: void* new typename; Allocates storage for an object of the required type, plus overhead. Then it calls the type s constructor, and returns a non-null pointer to the first byte of the new object. Create an object of type Book, initialized with the default constructor: Book* p1 = new Book; Create an object of type Book, initialized with parameters: Book* p2 = new Book(name, price); On failure, new throws a bad_alloc exception.

... 17/30 Dynamic Allocation in C++ Allocation Operator - new[] Used to allocate an array of objects void* new TypeName[n] ; Allocate a dynamic array of n objects of the named type. Initialize all of these objects using the default constructor for the type. Return a pointer to the first byte of the array. Prior to the first byte of the array will be two long integers for use when the array is freed: 1. the total length of the allocation, including overhead 2. the number of objects in the array.

... 18/30 Dynamic Allocation in C++ Deallocation Operator - delete This operator is part of the core language. It deletes a single object. Basic syntax: delete pp; where pp is a pointer to an object created by calling new. The system will use the number stored in the location prior to the first byte of the object and return that many bytes to the pool of reusable storage. You must not try to use an object after you delete it. If you never call new in your program, you must never call delete.

... 19/30 Dynamic Allocation in C++ Deallocation Operator - delete[] Deallocate an array of objects and call the destructor for each object in the array. Basic syntax: delete pa; where pa is a pointer to an array of objects created by new[]. pa must point at the first byte of the first array slot, not somewhere in the middle of the array. The system will use the two numbers stored in the locations prior to the first byte of the array: 1. First, the number of objects in the array is used to loop through the array and call the base-type destructor for each object in it. This is necessary if the constructor or functions for the base type of the array ever attach new parts to the objects in the array. 2. Then the total allocation size is used to return the array, itself, to the reusable storage pool.

... 20/30 Using Dynamic Arrays Using Dynamic Arrays FlexArrays An Application of FlexArrays

... 21/30 Using Dynamic Arrays FlexArrays in C FlexArray: A growing array of objects We can use realloc to create arrays that grow (like a vector in C++). When the data array is full, and we need to store more data into it, we simply tell it to grow. To grow, it will call realloc() to double its current capacity and copy the data into the new space. Then the new data can be stored in slot n, the first slot of the extended portion of the array. typedef struct { int n, max; BT* data; } FlexArray;

... 22/30 Using Dynamic Arrays FlexArrays in C FlexArray Functions #define MAX 10 void setup( FlexArray* f ) { f->max = MAX; f->n = 0; f->data = malloc( MAX * sizeof(bt) ); } void grow( FlexArray* f ) { f->max *= 2; f->data = realloc(f->data, f->max*sizeof(bt)); } void insert( FlexArray* f, BT b ) { if (f->max == f->n) grow(f); f->data[n++] = b; }

... 23/30 Using Dynamic Arrays An Application of FlexArrays The Username List This example introduces a dynamic FlexArray used to store username/password pairs. Features: One file, main.c, contains main. We have the tools module (tools.h and tools.c), as usual, In addition, we have a third code module (flex.h and flex.c) that defines FlexArrays and the base type, User. In a fully developed application, the User definitions would be in their own module with.h and.c files. The subdirectory also contains the input file. Here, we simply read the file of data and print it out. In a real application, functionality could be added

... 24/30 Using Dynamic Arrays An Application of FlexArrays A FlexArray of Users is created in the Username program. After setup, line 21. EUsers 0 4 After adding 4 users, line 54. andy beth charlie daphne EUsers 4 4 homebody2 noandyes DoubleDipper chickchaser101

... 25/30 Using Dynamic Arrays An Application of FlexArrays The FlexArray grows at run time. EUsers 4 8 When the fifth line is read the array grows: andy beth charlie daphne noandyes homebody2 DoubleDipper chickchaser101 The array will grow again when the 9th data item is read.

... 26/30 Using Dynamic Arrays An Application of FlexArrays Using the FlexArray Module The FlexArray code can be used in your own programs with very little modification. In flex.h, istead of the typedef for User, define the type of object you will be using in your program. Change the typedef for BT to name your new type instead of user. In flex.c, go to the printk() function and change it to print the parts of your new type in an attractive format. If possible, print it on one line. Add the modified flex.c and flex.h to your project.

... 27/30 Low-level Memory Operations IV. Low-level Memory Operations

... 28/30 Low-level Memory Operations Generic Operations The ctype and string libraries support operations specific for characters and strings. There are also generic operations that work on any type of data: memset, memcpy and memmove store into memory. memchr is like strnchr. memcmp is like strncmp. These low-level functions were used to implement the string library functions, but they can also be used for other purposes. They give us an efficient way to do simple things with blocks of bits.

... 29/30 Low-level Memory Operations Store into Memory void* memset(void *b, int c, size_t len); Write len bytes of value c (converted to an unsigned char) to the byte string b. void* memcpy(void* dest,const void* src,size_t n) Copies n bytes from src into dest and returns the address src. This may not work correctly for overlapping memory regions but often is faster than memmove(). void* memmove(void* to,const void* src,size_t n) Copies n characters from src into to and returns the address src. This works correctly for overlapping memory regions.

... 30/30 Low-level Memory Operations Search and Compare void* memchr(const void *s, int c, size_t n) Locate the first occurrence of c (converted to an unsigned char) in string s. Return a pointer to that byte, or NULL if no such byte exists within n bytes. int memcmp(const void *p,const void *q,size_t n) Compare the first n byes starting at address p to the first n bytes starting at q. Return a negative value if p is lexicographically less than q, 0 if they are equal, or a positive value if p is greater than q.