Example: Runtime Memory Allocation: Example: Dynamical Memory Allocation: Some Comments: Allocate and free dynamic memory

Size: px
Start display at page:

Download "Example: Runtime Memory Allocation: Example: Dynamical Memory Allocation: Some Comments: Allocate and free dynamic memory"

Transcription

1 Runtime Memory Allocation: Examle: All external and static variables Global systemcontrol Suose we want to design a rogram for handling student information: tyedef struct { All dynamically allocated variables malloc, realloc, calloc All auto variables and function call control information Hea Free area Stack user control systemcontrol char name[20]; int grade; student; Question: how to create a table of student records? a) static array: student stable[max_students]; b) dynamic: Table? List? Introduction 1 Introduction 2 Dynamical Memory Allocation: C requires the number of items in an array to be known at comile time. Too big or too small? Dynamical memory allocation allow us to secify an array s size at run time. Two imortant library functions are malloc, which allocates sace from HEAP, and free, which returns the sace (allocated by malloc) back to HEAP for reuse later. Examle: /* allocate and free an array of students, with error check */ #include <stddef.h> // definition of NULL #include <stdlib.h> // definition for malloc/free student *table_create(int n){ student* t; if ((t = malloc(n*sizeof(student)))!= NULL) return t; rintf( table_create: dynamic allocation failed.\n ); exit(0); void table_free(student *t){ if (t!= NULL) free(t); Introduction 3 Introduction 4 Some Comments: Allocate and free dynamic memory #include <stdlib.h> Don t assume malloc will always succeed. Don t assume the dynamically allocated memory is initialized to zero. Don t modify the ointer returned by malloc. free only ointers obtained from malloc, and don t access the memory after it has been freed. Don t forget to free memory which is no longer in use (garbage). void* malloc (size_t n) allocates n bytes and returns a ointer to the allocated memory, the memory is not cleared void* realloc(void*, size_t n) changes the size of the memory block ointed to by to n bytes. The contents will be unchanged to the minimum of the old and new sizes. void* calloc(size_t m, size_t n) allocates memory for an array of m elements of n bytes each, and returns a ointer to the array. void free(void* ) frees the memory block ointed to by. n m old unchanged realloc n bytes each calloc Introduction 5 Introduction 6 1

2 Examle: student table To create a student table dynamically. (1) do not know how many students, (2) keyboard inut Requirement: table holds exact number of ointers to student records; student ** st Array of ointers student student /* creates a student record dynamically and returns the ointer to the student record */ student* make_student(char* name, int grade){ student* s; if ((s = malloc(sizeof (student))) == NULL){ rintf( make_student: dynamic allocation failed.\n ); exit(0); strcy(s->name, name); s->grade = grade; return s; student /* coy s to t, suose t long enough*/ void my_strcy(char* t, char* s){ while (*t++ = *s++); Introduction 7 Introduction 8 #define CHUNK 5 student** make_table(int* num){ int j = 0, maxs = CHUNK, grade; char name[20]; student** st; st = (student**) malloc(maxs*sizeof(student*)); while (2 == scanf( %s%d\n, name, &grade)){ if (j >= maxs){ maxs += CHUNK; st = (student**) realloc(st, maxs*sizeof(student*)); st[j++] = make_student(name, grade); if (j < maxs) st = (student**) realloc(st, j*sizeof(student*)); *num = j; return st; int main(){ student** cis2520; int num; cis2520 = make_table(&num); rintf( The total number of students: %d\n, num); // other rocessing maxs j j: counter of students maxs: number of entries in the table If the table is not big enough, Add another 5 entries; Uon comlete, if the table has unused entries, then return them. Note: we only exand or truncate the ointer array (st), student records are not changed. Introduction 9 Introduction 10 Nested dynamic memory allocation: suose : tyedef struct { char *name; // instead of char name[20] int grade; student; student* make_student(char* name, int grade){ student* s; if ((s = malloc (sizeof (student)))!= NULL && (s->name = malloc(strlen(name) + 1)))!= NULL){ strcy(s->name, name); s->grade = grade; return s; rintf( make_student: dynamic allocation failed. \n ); exit(0); void free_student(student* s){ free(s->name); free(s); // must release name field first Introduction 11 Introduction 12 2

3 Linked list: A linked list reresents a sequence: Every node but one has a redecessor, and every node but one has a successor. t tail /* recursive definition */ tyedef struct node { int data; // whatever useful in the node struct node* next; // link to the next node node; Examle: student list data structure: tyedef structstudent{ char name[20]; int grade; struct student* next; student; make_student function not changed Introduction 13 Introduction 14 student* make_list(int* num){ int j = 0, grade; char name[20]; student *s = NULL, *e = NULL; while (2 == scanf( %s%d\n, name, &grade)){ if (s == NULL) s = e = make_student(name, grade); else { j++; e->next = make_student(name, grade); e = e->next; if (e!= NULL) e->next = NULL; // last node of the list *num = j; return s; int main(){ student* cis2520; int num; cis2520 = make_list(&num); rintf( The total number of students: %d\n, num); // other rocessing cis2520 s e Introduction 15 Introduction 16 Other useful functions: /* find the student record wrt name */ student* find(student* s, char* name){ while (s && (strcm(s->name, name)!= 0)) s = s->next; return s; /* rint student list */ void rint_list(student* s){ while (s){ rintf( Name: %s Grade: %d \n, s->name, s->grade); s = s->next; Recursive versions of rint_list /* rint student list recursively (from to tail)*/ void rint_list_1(student* s){ if (s){ rintf( Name: %s Grade: %d \n, s->name, s->grade); rintf_list_1(s->next); /* rint student list recursively (from tail back to )*/ void rint_list_2(student* s){ if (s){ rintf_list_2(s->next); rintf( Name: %s Grade: %d \n, s->name, s->grade); Introduction 17 Introduction 18 3

4 /* add a new student record after s */ void add_after(student* s, char name*, int grade){ student* new = make_student(name, grade); // (1) new->next = s->next; // (2) s->next = new; // (3) add_after(before call): s A add_after(after call): s A B new (1) new (3) (2) B Q: can we do add_before? Introduction 19 /* delete the student record after s */ void delete_after(student* s){ student* old; if (!s!s->next) return; old = s->next; // (1) s->next = old->next; // (2) free(old); delete_after(before call): s old (1) A delete_after(after call): old s A (2) B B Introduction 20 Linked list vs Array: Array: static storage allocation storage is contiguous random access (index) insert and delete must shift existing data Linked List: dynamic storage allocation storage is not contiguous sequential access only insert and delete do not change existing data Ordered Linked List: Insert nodes in their sorted osition. tyedef struct node{ int data; struct node* next; node; d3 dn where <= <= d3 <= <= dn Introduction 21 Introduction 22 Question: how to insert dk into the list? Case 1: == NULL Case 2:dk should be inserted in front of the list dk <= dk dk dn Case 3:dk should be inserted after a node d3 dn <= dk <= d3 dk can we declare: void insert(node * hd, int data){ suose we have the code: node* = NULL; insert(, 2); insert(, 5); NO, because list will be modified in both Case 1 and Case 2. void insert(node ** h, int data){ node* = NULL; insert(&, 2); insert(&, 5); Introduction 23 Introduction 24 4

5 /* Version 1: insert a new node (data) into a list ointed to by *h */ void insert(node** h, int data){ node* new, * rev == NULL, *curr; new = make_node(data); // suose we have this function curr = *h; // get ointer while (curr && data > curr->data){ // find osition rev = curr; curr = curr->next; if (rev == NULL){ new->next = *h; *h = new; else { rev->next = new; new->next = curr; // or if (!rev) // insert in front // insert after rev /* Version 2: insert a new node (data) into a list ointed to by*h */ void insert(node** h, int data){ node dummy, *new, *; new = make_node(data); = &dummy; dummy.next = *h; while (->next && data > ->next->data) = ->next; new->next = ->next; ->next = new; *h = dummy.next; // suose we have this function // set in dummy // find osition // always insert after Introduction 25 Introduction 26 Version 1: *h Version 2: dummy *h while (curr && data > curr->data){ rev = curr; curr = curr->next; d3 dn while (->next && data > ->next ->data) = ->next; d3 dn Suose: A B C D E F G H node *, *, *q, *tem; int data; = ; q = NULL; Introduction 27 Introduction 28 /* delete the node (data) from a list ointed to by *h */ void delete(node** h, int data){ node dummy, *old, *; = &dummy; dummy.next = *h; // set in dummy while (->next && data!= ->next->data) // find osition = ->next; if (->next){ old = ->next; // get the node to be deleted ->next = ->next->next; free(old); // free the node *h = dummy.next; Doubly Linked List: A list which can be traversed either forward or backward: tyedef struct node{ int data; struct node* next; struct node* rev; node; Introduction 29 Introduction 30 5

6 Insert oeration: Insert oeration: insert_after: insert_before: new->next = ->next; // 1 (red link) new->next = ; // 1 (red link) new->rev = ; ->next = ->next->rev = new; // 2 (green link) // 3 (blue links) new->rev = ->rev; ->rev= ->rev->next = new; // 2 (green link) // 3 (blue links) new 3 1 new Introduction 31 Introduction 32 Examle: Suose we have a doubly linked list: (1) find the mid node, (2) along mid s rev link, decrease each node value by 2, along mid s next link (include mid node), increase each node value by mid +5 d3 d4 d5 #define NEXT 0 #define PREV 1 tyedef struct node{ int data; struct node *link[2]; node; void traverse(node*, int dir, void (*f)(node*)){ while (){ (*f)(); // call function f with argument = ->link[dir]; void dec2(node* ){ ->data -= 2; void inc5(node* ){ ->data += 5; Introduction 33 Introduction 34 void rocessing(node* ){ node* mid = ; while ( && ->link[next] && ->link[next]->link[next]){ mid = mid->link[next]; = ->link[next]->link[next]; traverse(mid, PREV, dec2); // any roblem here? traverse(mid, NEXT, inc5); Function Pointer: tye (*f)(arameter_list); Generic Functions: A generic function is one that can work on any underlying C data tye. Generic functions allow us to reuse rograms by adding a small iece of tye-secific code. For examle, standard C library rovides two generic functions: bsearch searches an arbitrary array, and qsort sorts an arbitrary array. Function name is the ointer to that function. Introduction 35 Introduction 36 6

7 Review of Pointers to Functions: A ointer to a function contains the address of the function in memory. Similar to an array name which is the starting address of the first array element, a function name is the starting address of the function code. Pointers to functions can be assed to functions, returned from functions, stored in an array, and assigned to other function ointers. Pointers to Functions: int comare(int a, int b){ // imlementation int main(){ int cr1, cr2; int (*f)(int, int); // declare a ointer to function f = comare; // assign a function ointer tof cr1 = (*f)(2, 3); // call the function cr2 = f(2, 3); // same as above but not recommended Introduction 37 Introduction 38 Binary search function: binary search is used to find a target value in a sorted table. we start by comaring the target value with the table s middle element. since the table is sorted, so if the target is larger, we can ignore all values smaller than the middle element, and vice versa. We sto when we ve found the target or no values left to search. int* bsearch(int target, int *table, int n){ int *min = table; int *max = table + (n 1); int *mid; int k = n/2; while (min < max) { mid = min + k; if (target == *mid) return mid; else if (target > *mid) min = mid + 1; else max = mid - 1; k /= 2; return NULL; Introduction 39 Introduction 40 Generic Binary Search: void * bserach(const void *target, const void *table, size_t n, size_t size, int (*cmf)(const void *, const void*)); min target = mid min mid max max target: a ointer to the element we are searching for table: the array we are searching n: the size of the array size: the size of an array element cmf: a ointer to a function to comare the target and an element table target n size min mid max Target element Introduction 41 Introduction 42 7

8 bsearch Function: void * bserach(const void *target, const void *table, size_t n, size_t size, int (*cmf)(const void *, const void*)){ void *min = table, *max = table + (n 1)*size; void *mid; int k = n/2; int cr; while (min < max) { mid = min + k*size; cr = (*cmf )(target, mid) ; if (cr == 0) return mid; else if (cr > 0) min = mid + size; else max = mid - size; k /= 2; return NULL; Invoking bsearch: bsearch returns a ointer to the matching array element if it finds one, or NULL otherwise. Suose we have an int table inttable and a string table stringtable, we might call: int key = 78; int* i = bsearch(&key, inttable, ISIZE, sizeof(int), cmint); char* s = bsearch( Tom Wilson, stringtable, SSIZE, sizeof (stringtable[0]), cmstr); Introduction 43 Introduction 44 Tye-secific Functions: int cmint(const void *t, const void *e){ int it = *(int*) t; // get target value int ie = *(int*) e; // get array element value return (it == ie)? 0 : ((it < ie)? 1 : 1); int cmstr(const void *t, const void *e){ char *ct = (char*) t; // casting target to char ointer char *ce = *(char**) e; // get array element value (a char ointer) return strcm(ct, ce); (1) Write a comarison function: int cmstudent(const void* t, const void *s); which calls strcm to comare two student names. (2) suose a new student and a ointer variable are defined as follows: struct student s = {"John Smith", 21; struct student *; Write the call statement to bsearch to find if s is in stable and assign the returned value to. Introduction 45 Introduction 46 8

Linear Data Structure Linked List

Linear Data Structure Linked List . Definition. Reresenting List in C. Imlementing the oerations a. Inserting a node b. Deleting a node c. List Traversal. Linked imlementation of Stack 5. Linked imlementation of Queue 6. Circular List

More information

14. Memory API. Operating System: Three Easy Pieces

14. Memory API. Operating System: Three Easy Pieces 14. Memory API Oerating System: Three Easy Pieces 1 Memory API: malloc() #include void* malloc(size_t size) Allocate a memory region on the hea. w Argument size_t size : size of the memory block(in

More information

Lecture06: Pointers 4/1/2013

Lecture06: Pointers 4/1/2013 Lecture06: Pointers 4/1/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Pointers A ointer is a variable that contains the (memory) address of another variable What is a memory address?

More information

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first Ch. 17: Linked Lists 17.1 Introduction to Linked Lists! A data structure reresenting a list! A series of nodes chained together in sequence CS 2308 Sring 2015 Jill Seaman - Each node oints to one other

More information

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

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Dynamic Memory Management Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Dynamic Memory Allocation Dynamic memory allocation is used to

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly

More information

Storage Allocation CSE 143. Pointers, Arrays, and Dynamic Storage Allocation. Pointer Variables. Pointers: Review. Pointers and Types

Storage Allocation CSE 143. Pointers, Arrays, and Dynamic Storage Allocation. Pointer Variables. Pointers: Review. Pointers and Types CSE 143 Pointers, Arrays, and Dynamic Storage Allocation [Chater 4,. 148-157, 172-177] Storage Allocation Storage (memory) is a linear array of cells (bytes) Objects of different tyes often reuire differing

More information

Dynamic Data Structures. CSCI 112: Programming in C

Dynamic Data Structures. CSCI 112: Programming in C Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

Memory (Stack and Heap)

Memory (Stack and Heap) Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03

More information

Optimizing Dynamic Memory Management!

Optimizing Dynamic Memory Management! Otimizing Dynamic Memory Management! 1 Goals of this Lecture! Hel you learn about:" Details of K&R hea mgr" Hea mgr otimizations related to Assignment #6" Faster free() via doubly-linked list, redundant

More information

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

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12 Week 9 Part 1 Kyle Dewey Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2 Dynamic Allocation Recall... Dynamic memory allocation allows us to request memory on the fly

More information

Definition. Pointers. Outline. Why pointers? Definition. Memory Organization Overview. by Ziad Kobti. Definition. Pointers enable programmers to:

Definition. Pointers. Outline. Why pointers? Definition. Memory Organization Overview. by Ziad Kobti. Definition. Pointers enable programmers to: Pointers by Ziad Kobti Deinition When you declare a variable o any tye, say: int = ; The system will automatically allocated the required memory sace in a seciic location (tained by the system) to store

More information

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

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27 Midterm #2 Review 1 Time and Location The midterm will be given in class during normal class hours, 11:00a.m.-12:15p.m.,

More information

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic Memory Allocation (and Multi-Dimensional Arrays) Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan

More information

Cpt S 122 Data Structures. Data Structures

Cpt S 122 Data Structures. Data Structures Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation

More information

BBM 201 DATA STRUCTURES

BBM 201 DATA STRUCTURES BBM 201 DATA STRUCTURES Lecture 8: Dynamically Allocated Linked Lists 2017-2018 Fall int x; x = 8; int A[4]; An array is stored as one contiguous block of memory. How can we add a fifth element to the

More information

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

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space Dynamic Memory Allocation All variables, arrays, structures and unions that we worked with so far are statically allocated,

More information

C Structures & Dynamic Memory Management

C Structures & Dynamic Memory Management C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail

More information

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

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship

More information

Who. Winter Compiler Construction Generic compiler structure. Mailing list and forum. IC compiler. How

Who. Winter Compiler Construction Generic compiler structure. Mailing list and forum. IC compiler. How Winter 2007-2008 Comiler Construction 0368-3133 Mooly Sagiv and Roman Manevich School of Comuter Science Tel-Aviv University Who Roman Manevich Schreiber Oen-sace (basement) Tel: 640-5358 rumster@ost.tau.ac.il

More information

POINTER AND ARRAY SUNU WIBIRAMA

POINTER AND ARRAY SUNU WIBIRAMA POINTER AND ARRAY SUNU WIBIRAMA Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation Basic Pointer 3 Pointers A pointer is a reference to another variable (memory location) in a program

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store) Lecture 29 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 29: Linked Lists 19-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor: Vlado Keselj Previous

More information

Heap Arrays and Linked Lists. Steven R. Bagley

Heap Arrays and Linked Lists. Steven R. Bagley Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our

More information

Secure Software Programming and Vulnerability Analysis

Secure Software Programming and Vulnerability Analysis Secure Software Programming and Vulnerability Analysis Christopher Kruegel chris@auto.tuwien.ac.at http://www.auto.tuwien.ac.at/~chris Heap Buffer Overflows and Format String Vulnerabilities Secure Software

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

Chapter 19 Data Structures -struct -dynamic memory allocation

Chapter 19 Data Structures -struct -dynamic memory allocation Chapter 19 Data Structures -struct -dynamic memory allocation Data Structures A data structure is a particular organization of data in memory. We want to group related items together. We want to organize

More information

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allow for creation

More information

Introduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th

Introduction to Computer Systems /18 243, fall th Lecture, Oct. 22 th Introduction to Computer Systems 15 213/18 243, fall 2009 16 th Lecture, Oct. 22 th Instructors: Gregory Kesden and Markus Püschel Today Dynamic memory allocation Process Memory Image %esp kernel virtual

More information

Dynamically Allocated Memory in C

Dynamically Allocated Memory in C Dynamically Allocated Memory in C All throughout the C course (COP 3223), all examples of variable declarations were statically allocated memory. The word static means not changing while the word dynamic

More information

Dynamic Data Structures (II)

Dynamic Data Structures (II) Lecture 23 Dynamic Data Structures (II) CptS 121 Summer 2016 Armen Abnousi Data Structure Data structures are different ways of organizing data in computer We design new data structures to make the programs

More information

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved. Chapter 14 Dynamic Data Structures Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. 12-1 Dynamic Data Structure Usually, so far, the arrays and strings we

More information

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24 Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program

More information

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation CS61, Lecture 10 Prof. Stephen Chong October 4, 2011 Announcements 1/2 Assignment 4: Malloc Will be released today May work in groups of one or two Please go to website and enter

More information

Binghamton University. CS-211 Fall Dynamic Memory

Binghamton University. CS-211 Fall Dynamic Memory Dynamic Memory Static Memory Define variables when we write code When we write the code we decide What the type of the variable is How big array sizes will be etc. These cannot change when we run the code!

More information

Pointers (1A) Young Won Lim 10/18/17

Pointers (1A) Young Won Lim 10/18/17 Pointers (1A) Coyright (c) 2010-2013 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version

More information

Applications of Pointers (1A) Young Won Lim 4/11/18

Applications of Pointers (1A) Young Won Lim 4/11/18 (1A) Coyright (c) 2010-2018 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version ublished

More information

Applications of Pointers (1A) Young Won Lim 2/27/18

Applications of Pointers (1A) Young Won Lim 2/27/18 Alications of (1A) Coyright (c) 2010-2018 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

CMPS 105 Systems Programming. Prof. Darrell Long E2.371 + CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 7: The Environment of a UNIX process + Introduction + The main() fuction n int main(int argc, char* argv[]); n argc =

More information

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313. NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313 http://www.csee.umbc.edu/courses/undergraduate/313/fall11/" Programming in C! Advanced Pointers! Reminder! You can t use a pointer until it points

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

Heap Arrays. Steven R. Bagley

Heap Arrays. Steven R. Bagley Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,

More information

Applications of Pointers (1A) Young Won Lim 3/14/18

Applications of Pointers (1A) Young Won Lim 3/14/18 (1A) Coyright (c) 2010-2018 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version ublished

More information

Applications of Pointers (1A) Young Won Lim 3/21/18

Applications of Pointers (1A) Young Won Lim 3/21/18 (1A) Coyright (c) 2010-2018 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version ublished

More information

Pointers and Memory Allocation p. 1. Brooklyn College. Michael Lampis. CISC 3130 Notes. Pointers and Memory Allocation

Pointers and Memory Allocation p. 1. Brooklyn College. Michael Lampis. CISC 3130 Notes. Pointers and Memory Allocation Pointers and Memory Allocation CISC 3130 Notes Michael Lamis mlamis@cs.ntua.gr Brooklyn College Pointers and Memory Allocation. 1 int x; Pointers x Pointers and Memory Allocation. 2 Pointers int x; int

More information

Dynamic Memory Allocation. Gerson Robboy Portland State University. class20.ppt

Dynamic Memory Allocation. Gerson Robboy Portland State University. class20.ppt Dynamic Memory Allocation Gerson Robboy Portland State University class20.ppt Harsh Reality Memory is not unbounded It must be allocated and managed Many applications are memory dominated Especially those

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

CMPE-013/L. Introduction to C Programming

CMPE-013/L. Introduction to C Programming CMPE-013/L Introduction to C Programming Gabriel Hugh Elkaim Winter 2015 and memory Pointer/array equivalency Pointer arithmetic and the stack and strings Arrays of ointers 1 Syntax tye *trname; How to

More information

CP2 Revision. theme: dynamic datatypes & data structures

CP2 Revision. theme: dynamic datatypes & data structures CP2 Revision theme: dynamic datatypes & data structures structs can hold any combination of datatypes handled as single entity struct { }; ;

More information

Applications of Pointers (1A) Young Won Lim 3/31/18

Applications of Pointers (1A) Young Won Lim 3/31/18 (1A) Coyright (c) 2010-2018 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version ublished

More information

Applications of Pointers (1A) Young Won Lim 1/5/18

Applications of Pointers (1A) Young Won Lim 1/5/18 Alications of (1A) Coyright (c) 2010-2017 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later

More information

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

Memory Organization. The machine code and data associated with it are in the code segment Memory Management Memory Organization During run time, variables can be stored in one of three pools : 1. Stack 2. Global area (Static heap) 3. Dynamic heap The machine code and data associated with it

More information

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

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

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

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =

More information

Pointers (1A) Young Won Lim 10/23/17

Pointers (1A) Young Won Lim 10/23/17 Pointers (1A) Coyright (c) 2010-2013 Young W. Lim. Permission is granted to coy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version

More information

Dynamic Allocation of Memory

Dynamic Allocation of Memory Dynamic Allocation of Memory Lecture 5 Section 9.8 Robb T. Koether Hampden-Sydney College Wed, Jan 24, 2018 Robb T. Koether (Hampden-Sydney College) Dynamic Allocation of Memory Wed, Jan 24, 2018 1 / 34

More information

Reminder: compiling & linking

Reminder: compiling & linking Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object

More information

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites: C Programming Code: MBD101 Duration: 10 Hours Prerequisites: You are a computer science Professional/ graduate student You can execute Linux/UNIX commands You know how to use a text-editing tool You should

More information

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation

COSC Software Engineering. Lectures 14 and 15: The Heap and Dynamic Memory Allocation COSC345 2013 Software Engineering Lectures 14 and 15: The Heap and Dynamic Memory Allocation Outline Revision The programmer s view of memory Simple array-based memory allocation C memory allocation routines

More information

CS 1613 Lecture 24. Figure 1. Program p01.

CS 1613 Lecture 24. Figure 1. Program p01. Consider a rogram that is required to find all values larger than the average in a list of integers. The list is stored in a file. The rogram must read and store the list to fulfill its requirement. The

More information

Lecture 04 Control Flow II. Stephen Checkoway University of Illinois at Chicago CS 487 Fall 2017 Based on Michael Bailey s ECE 422

Lecture 04 Control Flow II. Stephen Checkoway University of Illinois at Chicago CS 487 Fall 2017 Based on Michael Bailey s ECE 422 Lecture 04 Control Flow II Stehen Checkoway University of Illinois at Chicago CS 487 Fall 2017 Based on Michael Bailey s ECE 422 Function calls on 32-bit x86 Stack grows down (from high to low addresses)

More information

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

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures CS113: Lecture 9 Topics: Dynamic Allocation Dynamic Data Structures 1 What s wrong with this? char *big_array( char fill ) { char a[1000]; int i; for( i = 0; i < 1000; i++ ) a[i] = fill; return a; void

More information

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists Outline Briefly review the last class Pointers and Structs Memory allocation Linked lists C Structures and Memory Allocation A struct is a data structure that comprises multiple types, each known as a

More information

Chapter 19 Data Structures

Chapter 19 Data Structures Chapter 19 Data Structures Img src: reddit.com/r/programmerhumor 19-2 Data Structures A data structure is a particular organization of data in memory. We want to group related items together. We want to

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

My malloc: mylloc and mhysa. Johan Montelius HT2016

My malloc: mylloc and mhysa. Johan Montelius HT2016 1 Introduction My malloc: mylloc and mhysa Johan Montelius HT2016 So this is an experiment where we will implement our own malloc. We will not implement the world s fastest allocator, but it will work

More information

Memory Management. CS449 Fall 2017

Memory Management. CS449 Fall 2017 Memory Management CS449 Fall 2017 Life9mes Life9me: 9me from which a par9cular memory loca9on is allocated un9l it is deallocated Three types of life9mes Automa9c (within a scope) Sta9c (dura9on of program)

More information

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Darshan Institute of Engineering & Technology for Diploma studies Unit 4 Pointer A pointer is a variable that contains address or location of another variable. Pointer is a derived data type in C. Pointers contain memory address as their values, so they can also be used to

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations Reminder of midterm 1 Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations A New Example to see effect of E++ (better than the one in previous lecture) Purpose of showing

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

CS201: Lab #4 Writing a Dynamic Storage Allocator

CS201: Lab #4 Writing a Dynamic Storage Allocator CS201: Lab #4 Writing a Dynamic Storage Allocator In this lab you will write a dynamic storage allocator for C programs, i.e., your own version of the malloc, free and realloc routines. You are encouraged

More information

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

Memory Management I. two kinds of memory: stack and heap Memory Management I two kinds of memory: stack and heap stack memory: essentially all non-pointer (why not pointers? there s a caveat) variables and pre-declared arrays of fixed (i.e. fixed before compilation)

More information

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

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

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Dynamic Memory Allocation All variables, arrays, structures and unions that we worked with so far are statically allocated, meaning

More information

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University (13-2) Dynamic Data Structures I H&K Chapter 13 Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University Dynamic Data Structures (1) Structures that expand and contract

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Dynamic Memory Allocation I Nov 5, 2002

Dynamic Memory Allocation I Nov 5, 2002 15-213 The course that gives CMU its Zip! Dynamic Memory Allocation I Nov 5, 2002 Topics Simple explicit allocators Data structures Mechanisms Policies class21.ppt Harsh Reality Memory is not unbounded

More information

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics

CSCI-UA /2. Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics Slides adapted (and slightly modified) from: Clark Barrett Jinyang Li Randy Bryant Dave O Hallaron CSCI-UA.0201-001/2 Computer Systems Organization Lecture 19: Dynamic Memory Allocation: Basics Mohamed

More information

ECE 551D Spring 2018 Midterm Exam

ECE 551D Spring 2018 Midterm Exam Name: ECE 551D Spring 2018 Midterm Exam NetID: There are 6 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

Memory Management. CS31 Pascal Van Hentenryck CS031. Lecture 19 1

Memory Management. CS31 Pascal Van Hentenryck CS031. Lecture 19 1 Memory Management CS31 Pascal Van Hentenryck CS031 Lecture 19 1 Memory Management What is it? high-level languages abstract many aspects of memory management Support varies with the language Java (ML/Prolog/Lisp/Smalltalk)

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Fall 2018 Discussion 2: September 3, 2018

Fall 2018 Discussion 2: September 3, 2018 CS 61C C Basics Fall 2018 Discussion 2: September 3, 2018 1 C C is syntactically similar to Java, but there are a few key differences: 1. C is function-oriented, not object-oriented; there are no objects.

More information

Dynamic Memory Allocation

Dynamic Memory Allocation 1 Dynamic Memory Allocation Anne Bracy CS 3410 Computer Science Cornell University Note: these slides derive from those by Markus Püschel at CMU 2 Recommended Approach while (TRUE) { code a little; test

More information

Contents of Lecture 3

Contents of Lecture 3 Contents of Lecture 3 Repetition of matrices double a[3][4]; double* b; double** c; Terminology Linkage Types Conversions Jonas Skeppstedt (js@cs.lth.se) Lecture 3 2014 1 / 33 A global matrix: double a[3][4]

More information

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

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= &num;

More information

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

Dynamic Memory Allocation I

Dynamic Memory Allocation I Dynamic Memory Allocation I William J. Taffe Plymouth State University Using the Slides of Randall E. Bryant Carnegie Mellon University Topics Simple explicit allocators Data structures Mechanisms Policies

More information

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1 C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...

More information

DAY 3. CS3600, Northeastern University. Alan Mislove

DAY 3. CS3600, Northeastern University. Alan Mislove C BOOTCAMP DAY 3 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh and Pascal Meunier s course at Purdue Memory management 2 Memory management Two

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators

More information

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

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation

More information

Solution for Data Structure

Solution for Data Structure Solution for Data Structure May 2016 INDEX Q1 a 2-3 b 4 c. 4-6 d 7 Q2- a 8-12 b 12-14 Q3 a 15-18 b 18-22 Q4- a 22-35 B..N.A Q5 a 36-38 b N.A Q6- a 39-42 b 43 1 www.brainheaters.in Q1) Ans: (a) Define ADT

More information