Dynamic Memory Allocation and Linked Lists
|
|
- Derek Haynes
- 6 years ago
- Views:
Transcription
1 CSE 2421: Systems I Low-Level Programming and Computer Organization Dynamic Memory Allocation and Linked Lists Presentation I Read/Study: Reek Chapter 11 & 12 Gojko Babić Functions malloc and free void *malloc(size_t size); allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared. a returned pointer to the allocated memory is suitably aligned for any kind of variable. On error, this function return NULL. void free(void *ptr); frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. this function returns no value. g. babic Presentation I 2 1
2 Using malloc Function Here how a new "nameless" variable of type int can be created with a pointer addressing (pointing) that variable: int *p1; p1 = malloc(sizeof(int)); the new variable is referred to as *p1 and *p1 can be used anyplace an integer variable can, e.g. *p1=201; x = *p1 + 7; printf( %d, *p1); These type of variables are called dynamic variables: they are created while the program is running, an area of memory called the heap is reserved for dynamic variables; new dynamic variables use memory in the heap, if all of the heap is used, calls to malloc returns NULL. g. babic Presentation I 3 Using free Function When dynamic variables are no longer needed, they can be deleted and the memory they used is returned to the heap. To delete dynamic memory use free function: free (p); the memory previously allocated by p = malloc ( ) is back in the heap and the value of p is now undefined, i.e. it is not pointing to any memory. If another pointer variable was pointing to this dynamic variable, that pointer is also undefined Undefined pointer variables are called dangling pointers referencing a dangling pointer is usually disastrous for any running program g. babic Presentation I 4 2
3 Linux x86-64 Program Run-Time Memory Image Kernel virtual memory User stack (created at runtime) Memory invisible to user code %rsp Run-time heap (created by malloc) 0x Read/write data Read-only code and data Loaded from the executable file 0 bryant Presentation I 5 Simple Dynamic Memory Allocation int main() int *p1, *p2; p1 = malloc(sizeof(int)); *p1 = 42; p2 = p1; printf("\n*p1= %d *p2= %d", *p1, *p2); *p2=53; printf("\n*p1= %d *p2= %d", *p1, *p2); p1 = malloc(sizeof(int)); *p1 =88; printf("\n*p1= %d *p2= %d", *p1, *p2); Output: *p1= 42 *p2= 42 *p1= 53 *p2= 53 *p1= 88 *p2= 53 g. babic Presentation I 6 3
4 Simple Dynamic Memory Allocation (cont.) p1 = malloc(sizeof(int)); p1 = malloc(sizeof(int)); g. babic Presentation I 7 Dynamic Arrays Normal arrays require that the programmer determine the size of the array when the program is written and if the programmer estimates too large, memory is wasted, if the programmer estimates too small, the program may not work in some situations. A dynamic array is an array whose size is determined when the program is running, not when you write the program. A dynamic array of N elements of type double can be created this way: double *d; d = malloc(i*sizeof(double)); i is an int variable with positive value N, d can now be used as if it were an ordinary array, e.g. d[0], and d[j], or *d and *(d+j). When done with the array, its allocated memory should be returned to the heap; it is done like this: free(d); g. babic Presentation I 8 4
5 Dynamic 1D-Array of Structures: Version A struct stype char cx; int iy; ; int main() int i, N=10; struct stype *ptr; ptr = malloc(n*sizeof(struct stype)); // ptr==null? for (i=0; i<n; i++) if(i%2==0) ptr[i].cx='a'; else ptr[i].cx='b'; ptr[i].iy=i; for (i=0; i<n; i++) printf("\n %c %d", (ptr+i)->cx, (ptr+i)->iy); Output: A 0 B 1 A 2 B 3 A 4 B 5 A 6 B 7 A 8 B 9 The printf could be also written as: printf("\n %c %d", ptr[i].cx, ptr[i].iy); or printf("\n %c %d", (*(ptr+i)).cx, (*(ptr+i)).iy); g. babic Presentation I 9 Dynamic 1D-Array of Structures: Version B typedef struct char cx; int iy; stype; int main() int i, N=10; stype *ptr; ptr = malloc(n*sizeof(stype)); // ptr==null? for (i=0; i<n; i++) if(i%2==0) ptr[i].cx='a'; else ptr[i].cx='b'; ptr[i].iy=i; for (i=0; i<n; i++) printf("\n %c %d", (ptr+i)->cx, (ptr+i)->iy); ptr[i].cx= A ; could be written as: (*(ptr+i)).cx= A ; or (ptr+i)->cx= A ; Output: A 0 B 1 A 2 B 3 A 4 B 5 A 6 B 7 A 8 B 9 g. babic Presentation I 10 5
6 Dynamic 2-Dimentional Array: A Version #define COLS 5 int main(void) int (*rptr)[cols]; int nrows = 10; int i, j; rptr = malloc(nrows * COLS * sizeof(int)); if (rptr == NULL) printf( malloc didn t work ); return 0; for (i = 0; i < nrows; i++) for (j = 0; j < COLS; j++) rptr[i][j] = (i+1)*(j+1); // *(*(rptr+i)+j)) = (i+1)*(j+1); for (i = 0; i < nrows; i++) for (j = 0; j < COLS; j++) if(j==0)printf("\n"); printf("%8d", rptr[i][j]); // printf("%8d", *(*(rptr+i)+j)); return 0; Output: g. babic Presentation I 11 Dynamic 2-Dimentional Array: B Version #define COLS 5 typedef int RowArray[COLS]; int main(void) RowArray *rptr; int nrows = 10; int i, j; rptr = malloc(nrows * COLS * sizeof(int)); if (rptr == NULL) printf( malloc didn t work ); return 0; for (i = 0; i < nrows; i++) for (j = 0; j < COLS; j++) rptr[i][j] = (i+1)*(j+1); for (i = 0; i < nrows; i++) for (j = 0; j < COLS; j++) if(j==0)printf("\n"); printf("%8d", rptr[i][j]); // printf("%8d", *(*(rptr+i)+j)); return 0; Output: g. babic Presentation I 12 6
7 Nodes and Linked Lists A linked list is a list that can grow and shrink while the program is running and it is constructed using pointers, A linked list consists of structures that contain a pointer variable connecting them to other dynamic variables, A linked list can be visualized as items, drawn as boxes, connected to other items by arrows: nodes contain the data item(s) and a pointer that points to another node of the same type Example: typedef struct node char item[10]; int count; struct node *link; ListNode; This circular definition is allowed in C g. babic Presentation I 13 Nodes and Pointers The box labeled head is not a node, but a pointer variable pointing to the first node. Pointer variable head is declared as: ListNode* head; The boxes in the drawing represent the nodes of a linked list. The arrows in the drawing represent pointers. To change the number in the first node from 10 to 12, use this: (*head).count = 12; // assumed that head points to the first node. g. babic Presentation I 14 7
8 In the statement: (*head).count = 12; head is a pointer variable, so *head is the node that head points to; the parentheses are necessary because the dot operator (.) has higher precedence than the dereference operator (*). The arrow operator > combines the actions of the dereferencing operator and the dot operator to specify a member of a struct to by a pointer, e.g. the statement above can be written as head >count = 12; The defined constant NULL is used as an end marker for a linked list. A program can step through a list of nodes by following the pointers, but when it finds a node containing NULL, it knows it has come to the end of the list. g. babic Accessing Items in Node Presentation I 15 Accessing Items in Node (continued) head->count = 12; strcpy(head->item, bagels ); A linked list is a list of nodes in which each node has a member variable that is a pointer that points to the next node in the list. The pointer variable head, points to the first node. The last node contains a pointer set to NULL g. babic Presentation I 16 8
9 Building a Linked List Let's use a simple node definition: typedef struct node int data; struct node *link; ListNode; Now, we can declare the pointer variable head: ListNode *head; head is a pointer variable that will point to the first node of the list when the node is created. Next, we create the first node: head = malloc(sizeof(listnode)); head points to the first, and only, node in the list. Since head points to a node, we could give values to the member variables of the node: head >data = 3; head >link = NULL; //since this is the last node g. babic Presentation I 17 Empty Lists and Memory Leaks A list with nothing in it is called an empty list; that list has no nodes. The head pointer of an empty list is NULL, and any function written to manipulate a linked list should check to see if it works on the empty list. You might be tempted to add new node at the beginning of the list using the head pointer to construct another node: head = malloc(sizeof(listnode)); head >data = 12; But the node(s) that head used to point to is (are) now lost! Nodes that are lost by assigning their pointers new addresses are not accessible any longer and the program has no way to refer to those nodes even to free them and return to the heap. Programs that loose nodes have a memory leak and significant memory leaks can cause program crashes. g. babic Presentation I 18 9
10 Adding a Node at the Head of List 1. Set up new node: ListNode* temp_ptr; temp_ptr = malloc(sizeof(listnode)); temp_ptr->data = 12; g. babic 19 Locating a Node in a Linked List typedef struct node int data; struct node *link; ListNode; ListNode* PointToMe(ListNode *ptr, int target); /* This function returns a pointer to the node with data==target, or NULL if such doesn t exist; ptr should be the pointer to the first node of the list */ ListNode* PointToMe(ListNode *here, int target) if(here == NULL) return NULL; while (here->data!= target && here->link!=null) here= here->link; if(here->data == target) return here; return NULL; Presentation I 20 10
11 Locating a Node in a Linked List (cont.) 1. The list before the function call 2. After the function call: PointToMe (head, 6) target = 6 g. babic 5. Function returns value of pointer here 21 Inserting in the Middle of a Linked List 1. find pointer to a node after which new node should be inserted; let it be the pointer after_me; 2. create new node and update its value, such as: temp_ptr = malloc(sizeof(listnode)); temp_ptr->data=5; 3. Inserting: temp_ptr->link=after_me->link; after_me->link=temp_ptr; g. babic Presentation I 22 11
12 Removing a Node from a Linked List free(discard); If the node to be removed is the first node in the list: if (head == discard) head = discard >link; free(discard); g. babic Presentation I 23 Summary of Insert and Remove Inserting into a linked list requires only to change two pointers: inserting into a linked list is often more efficient than inserting into an array; using an array for the list would involve copying as many as all of the array elements to new locations to make room for the new item. To remove a node from a linked list: position one pointer to point at the node prior to the node to remove and position another pointer to point at the node to remove, perform: before >link = discard >link; return to the heap: free (discard); removing from a linked list is often more efficient than deleting from an array; using an array for the list would involve copying of all array elements to new locations to occupy room for the deleted item. g. babic Presentation I 24 12
13 A Double Linked List The node structure for a double linked list could be as follows: typedef struct node struct node *back_link; int data; struct node * forward_link; ListNode; g. babic Presentation I 25 Binary Tree The node structure for a binary tree could be as follows: typedef struct node int data; struct node * left_link; struct node *right_link; ListNode; g. babic Presentation I 26 13
Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15
Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15 Ziad Matni Dept. of Computer Science, UCSB The head of a List The box labeled head, in Display 13.1, is not a node, but
More informationCSC 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 informationProgramming in C/C Lecture 2
Programming in C/C++ 2005-2006 Lecture 2 http://few.vu.nl/~nsilvis/c++/2006 Natalia Silvis-Cividjian e-mail: nsilvis@few.vu.nl vrije Universiteit amsterdam News Check announcements on the C/C++ website
More informationClass 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 informationChapter 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= #
More informationHeap 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 informationo 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 informationLinked Lists CS 16: Solving Problems with Computers I Lecture #16
Linked Lists CS 16: Solving Problems with Computers I Lecture #16 Ziad Matni Dept. of Computer Science, UCSB Material: Everything we ve done Homework, Labs, Lectures, Textbook Tuesday, 12/12 in this classroom
More informationLecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?
Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static
More informationIn 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 informationMemory 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 informationActually, C provides another type of variable which allows us to do just that. These are called dynamic variables.
When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called
More informationHeap 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 informationCS24 Week 2 Lecture 1
CS24 Week 2 Lecture 1 Kyle Dewey Overview C Review Void pointers Allocation structs void* (Void Pointers) void* Like any other pointer, it refers to some memory address However, it has no associated type,
More informationAnnouncements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1
Announcements assign due tonight No late submissions Labs start this week Very helpful for assign1 Goals for Today Pointer operators Allocating memory in the heap malloc and free Arrays and pointer arithmetic
More informationCOMP26120: Linked List in C (2018/19) Lucas Cordeiro
COMP26120: Linked List in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Linked List Lucas Cordeiro (Formal Methods Group) lucas.cordeiro@manchester.ac.uk Office: 2.28 Office hours: 10-11 Tuesday,
More informationCS 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 informationThe 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 informationUnderstanding Pointers
Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer
More informationCpt 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 informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Memory Management 2007-06-28 Scott Beamer, Instructor iphone Comes out Tomorrow CS61C L4 C Memory Management (1) www.apple.com/iphone
More informationDynamic 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, there are four library routines known as memory management
More informationMemory 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 informationCS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/
CS61C Machine Structures Lecture 4 C Structs & Memory Management 9/5/2007 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Structs (1) C String Standard Functions
More informationWeek 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 informationProgramming. 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 informationINITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS
INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria INITIALISING POINTER VARIABLES Pointer variables are declared by putting
More informationData Structure Series
Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after
More informationInstructions: Submit your answers to these questions to the Curator as OQ02 by the posted due date and time. No late submissions will be accepted.
Instructions: Submit your answers to these questions to the Curator as OQ02 by the posted due date and time. No late submissions will be accepted. For the next five questions, consider the function to
More informationCharacter Strings. String-copy Example
Character Strings No operations for string as a unit A string is just an array of char terminated by the null character \0 The null character makes it easy for programs to detect the end char s[] = "0123456789";
More informationCS61, 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 informationCS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/
CS61C Machine Structures Lecture 5 C Structs & Memory Mangement 1/27/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L05 C Structs (1) C String Standard Functions
More informationDynamic memory. EECS 211 Winter 2019
Dynamic memory EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/06dynamic.tgz tar zx $ cd 06dynamic 3 Oops! I made a mistake. In C, the declaration struct circle read_circle();
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia CS61C L05 C Structures, Memory Management (1) 2005-01-28 The
More informationMemory Allocation. General Questions
General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to
More informationCS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016
CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable
More informationCS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor
CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static
More informationLab 3. Pointers Programming Lab (Using C) XU Silei
Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions
More informationDynamic Memory Management
Dynamic Memory Management 1 Goals of this Lecture Help you learn about: Dynamic memory management techniques Garbage collection by the run-time system (Java) Manual deallocation by the programmer (C, C++)
More informationC 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 informationContent. 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 informationMemory 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 informationC Introduction. Comparison w/ Java, Memory Model, and Pointers
CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language
More informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
More informationToday s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.
Pointers/arrays Mechanics, syntax Underlying memory model Array indexing == pointer arithmetic As parameters Stack versus heap allocation Stack declaration, scope, lifetime Heap allocation/deallocation
More informationCpt S 122 Data Structures. Course Review Midterm Exam # 1
Cpt S 122 Data Structures Course Review Midterm Exam # 1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 1 When: Friday (09/28) 12:10-1pm Where:
More informationLectures 13 & 14. memory management
Lectures 13 & 14 Linked lists and memory management Courtesy of Prof. Garcia (UCB) CS61C L05 Introduction to C (pt 3) (1) Review Pointers and arrays are virtually same C knows how to increment pointers
More informationIn this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021
Chapter 9 In this chapter, you will learn about: Pointers Dynamic Arrays Address A pointer is the memory address of a variable 1022 1023 x Recall, Computer memory is divided into cells (or bytes) 1024
More informationBBM 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 informationCSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine
More informationCSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation
CSCI 2132 Software Development Lecture 29: Dynamic Memory Allocation Instructor: Vlado Keselj Faculty of Computer Science Dalhousie University 22-Nov-2017 (29) CSCI 2132 1 Previous Lecture Protecting header
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 5 C Memory Management Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia CS 61C L04 C Structures, Memory Management (1) 2004-09-10 Barry
More informationMemory (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 informationReview: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc
CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array
More informationUnit IV & V Previous Papers 1 mark Answers
1 What is pointer to structure? Pointer to structure: Unit IV & V Previous Papers 1 mark Answers The beginning address of a structure can be accessed through the use of the address (&) operator If a variable
More informationDynamic Allocation in C
Dynamic Allocation in C C Pointers and Arrays 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically,
More informationC Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha
C Tutorial Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha CS 370 - Operating Systems - Spring 2019 1 Outline What is a pointer? & and * operators
More informationMemory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.
Memory and Addresses Memory is just a sequence of byte-sized storage devices. 1 The bytes are assigned numeric addresses, starting with zero, just like the indexing of the cells of an array. It is the
More informationLinked Data Representations. Data Structures and Programming Techniques
Linked Data Representations 1 Linked Data Representations Linked data representations such as lists, stacks, queues, sets and trees are very useful in Computer Science and applications. E.g., in Databases,
More informationLinked Data Representations
Linked Data Representations Manolis Koubarakis 1 Linked Data Representations Linked data representations such as lists, stacks, queues, sets and trees are very useful in computer science and applications.
More informationLecture 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 informationChapter 9. Pointers and Dynamic Arrays
Chapter 9 Pointers and Dynamic Arrays Overview 9.1 Pointers 9.2 Dynamic Arrays Slide 9-2 9.1 Pointers Pointers n A pointer is the memory address of a variable n Memory addresses can be used as names for
More informationCMSC 341 Lecture 2 Dynamic Memory and Pointers
CMSC 341 Lecture 2 Dynamic Memory and Pointers Park Sects. 01 & 02 Based on earlier course slides at UMBC Today s Topics Stack vs Heap Allocating and freeing memory new and delete Memory Leaks Valgrind
More informationStructures and Pointers
Structures and Pointers Comp-206 : Introduction to Software Systems Lecture 11 Alexandre Denault Computer Science McGill University Fall 2006 Note on Assignment 1 Please note that handin does not allow
More informationMemory 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 informationIntroduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers
Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities
More informationKey C Topics: Tutorial Pointers, Dynamic Memory allocation, Valgrind and Makefile CS370
Key C Topics: Tutorial Pointers, Dynamic Memory allocation, Valgrind and Makefile CS370 Outline Pointers in C & and * operators Pointers with Arrays and Strings Dynamic memory allocation malloc() and free()
More information11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {
This document contains the questions and solutions to the CS107 midterm given in Spring 2016 by instructors Julie Zelenski and Michael Chang. This was an 80-minute exam. Midterm questions Problem 1: C-strings
More informationDynamic Allocation of Memory
Dynamic Allocation of Memory Lecture 4 Sections 10.9-10.10 Robb T. Koether Hampden-Sydney College Fri, Jan 25, 2013 Robb T. Koether (Hampden-Sydney College) Dynamic Allocation of Memory Fri, Jan 25, 2013
More informationQuiz 0 Review Session. October 13th, 2014
Quiz 0 Review Session October 13th, 2014 Topics (non-exhaustive) Binary. ASCII. Algorithms. Pseudocode. Source code. Compiler. Object code. Scratch. Statements. Boolean expressions. Conditions. Loops.
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationArrays and Memory Management
Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted
More informationRecitation #11 Malloc Lab. November 7th, 2017
18-600 Recitation #11 Malloc Lab November 7th, 2017 1 2 Important Notes about Malloc Lab Malloc lab has been updated from previous years Supports a full 64 bit address space rather than 32 bit Encourages
More informationCS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.
CS 33 Intro to Storage Allocation CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved. A Queue head typedef struct list_element { int value; struct list_element
More informationCS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver
CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver http://inst.eecs.berkeley.edu/~cs61c/sp16 1 Agenda Pointers Arrays in C 2 Address vs. Value Consider
More informationCS113: 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 informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationCompiling C Programs Into X86-64 Assembly Programs
CSE 2421: Systems I Low-Level Programming and Computer Organization Compiling C Programs Into X86-64 ssembly Programs Part C: rrays & Structure Read/Study: Bryant 3.8, 3.9.1 Gojko Babić 04-02-2018 Statement:
More informationch = 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 informationHow about them A s!! Go Oaktown!! CS61C - Machine Structures. Lecture 4 C Structures Memory Management Dan Garcia.
How about them A s!! Go Oaktown!! CS61C - Machine Structures Lecture 4 C Structures Memory Management 2002-09-05 Dan Garcia (www.cs.berkeley.edu/~ddgarcia) Dave Patterson (www.cs.berkeley.edu/~patterson)
More information19-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 informationTHE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I
THE GOOD, BAD AND UGLY ABOUT POINTERS Problem Solving with Computers-I The good: Pointers pass data around efficiently Pointers and arrays 100 104 108 112 116 ar 20 30 50 80 90 ar is like a pointer to
More informationApplied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011
Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 4, C programming: pointer, array, struct, list A. Maki, C. Edlund Pointer
More informationArrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.
Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example
More informationPointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple
More information[0569] p 0318 garbage
A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the
More informationElementary Data Structures: Lists
Elementary Data Structures: Lists CSE 2320 Algorithms and Data Structures Based on presentation by Vassilis Athitsos University of Texas at Arlington 1 Pointers What to Review Pointers and Memory : http://cslibrary.stanford.edu/102/pointersandmemory.pdf
More informationC Programming Basics II
C Programming Basics II Xianyi Zeng xzeng@utep.edu Department of Mathematical Sciences The University of Texas at El Paso. September 20, 2016. Pointers and Passing by Address Upon declaring a variable,
More informationMPATE-GE 2618: C Programming for Music Technology. Unit 5.1
MPATE-GE 2618: C Programming for Music Technology Unit 5.1 Review: automatic vs. static variables Variables declared and passed to functions are automatic variables. As soon as you leave the function,
More informationMemory Allocation III
Memory Allocation III CSE 351 Spring 2017 Instructor: Ruth Anderson Teaching Assistants: Dylan Johnson Kevin Bi Linxing Preston Jiang Cody Ohlsen Yufang Sun Joshua Curtis Administrivia Homework 5 Due Wed
More informationPointers, Arrays, Memory: AKA the cause of those Segfaults
Computer Science 61C Spring 2018 Wawrzynek and Weaver Pointers, Arrays, Memory: AKA the cause of those F@#)(#@*( Segfaults 1 Agenda Computer Science 61C Spring 2018 Pointers Arrays in C Memory Allocation
More informationChapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo
Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this
More informationApplied Programming and Computer Science, DD2325/appcs14 PODF, Programmering och datalogi för fysiker, DA7011
Applied Programming and Computer Science, DD2325/appcs14 PODF, Programmering och datalogi för fysiker, DA7011 Lecture 4, C programming: pointer, array, struct, list A. Maki, C. Edlund November 2014 Pointer
More informationMODULE 5: Pointers, Preprocessor Directives and Data Structures
MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two
More informationC-types: basic & constructed. C basic types: int, char, float, C constructed types: pointer, array, struct
C-types: basic & constructed C basic types: int, char, float, C constructed types: pointer, array, struct Memory Management Code Global variables in file (module) Local static variables in functions Dynamic
More informationC Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008
C Programming Language: C ADTs, 2d Dynamic Allocation Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008 Overview Row major format 1 and 2-d dynamic allocation struct
More informationLecture Notes on Memory Management
Lecture Notes on Memory Management 15-122: Principles of Imperative Computation Frank Pfenning Lecture 22 November 11, 2010 1 Introduction Unlike C0 and other modern languages like Java, C#, or ML, C requires
More informationData Structures and Algorithms for Engineers
04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University
More informationLow-Level C Programming. Memory map Pointers Arrays Structures
Low-Level C Programming Memory map Pointers Arrays Structures Memory Map 0x7FFF_FFFF Binaries load at 0x20000 by default Stack start set by binary when started Stack grows downwards You will need one stack
More informationVariation of Pointers
Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before
More information