Computer Science 210 Computer Organization Pointers and Dynamic Storage.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Carnegie Mellon 1 Dynamic Memory Allocation: Basic Concepts : Introduction to Computer Systems 17 th Lecture, Oct. 21, 2010 Instructors: Randy Bryant.
Chapter 6 Data Types
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Chris Riesbeck, Fall 2007 Dynamic Memory Allocation Today Dynamic memory allocation – mechanisms & policies Memory bugs.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
1 CSE 303 Lecture 12 structured data reading: Programming in C Ch. 9 slides created by Marty Stepp
CS61C L05 C Structures, Memory Management (1) Garcia, Spring 2005 © UCB Lecturer PSOE Dan Garcia inst.eecs.berkeley.edu/~cs61c.
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
CS61C L4 C Memory Management (1) Beamer, Summer 2007 © UCB Scott Beamer, Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4.
Pointers and Dynamic Memory Allocation. Dynamic Data Suppose we write a program to keep track of a list of students How many student records should we.
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Memory Allocation Ming Li Department.
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure C Programming Concepts Ming Li.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
CS Data Structures Chapter 4 Lists.
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Computer Science 210 Computer Organization Pointers.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 3 – August 28, 2001.
Linked Lists EENG 212 ALGORITHMS And DATA STRUCTURES.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Cs641 pointers/numbers.1 Overview °Stack and the Heap °malloc() and free() °Pointers °numbers in binary.
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Data Structure & Algorithms
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Dale Roberts, Lecturer Data Structure.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Dynamic Storage Allocation
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
ENEE150 Discussion 07 Section 0101 Adam Wang.
malloc(): Dynamic Memory Management
CSC172 Data Structures Linked Lists (C version)
Dynamic Memory Allocation
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Memory Allocation CS 217.
CSE 214 – Computer Science II Pointers & Memory Management
EENG 212 ALGORITHMS And DATA STRUCTURES
Review & Lab assignments
Class and Objects In a class, all the functions that operate on the data structure are grouped together in one place along with the data Like a struct.
Dynamic Memory.
Presentation transcript:

Computer Science 210 Computer Organization Pointers and Dynamic Storage

Heap Allocation and Deallocation The C programmer must run functions to allocate and deallocate memory for dynamic storage (referenced by pointers) malloc allocates a block of storage from the heap free returns storage to the heap

int *intPtr; Declare a Pointer to an int intPtr The variable is uninitialized and contains garbage, but it can point to an int eventually

#include int *intPtr = NULL; // NULL is the same as 0 Declare and Initialize to NULL 0 intPtr The variable is initialized to the NULL pointer, which can now be accessed

#include int *intPtr = malloc(sizeof(int)); Declare and Initialize with malloc intPtr The variable now points to a new storage area for an int, but this storage contains garbage malloc expects an integer representing the size of the storage needed The sizeof function takes a type as an argument and returns the number of bytes needed for a value of that type malloc returns a pointer to the first byte of the storage

#include int *intPtr = malloc(sizeof(int)); (*intPtr) = 69; printf("%d\n", *intPtr); Access via Dereference with * intPtr The variable now points to storage that has a program-supplied value 69 The * operator accesses the cell pointed to The pointer must point to a cell * has a lower precedence than =

#include int *intPtr = malloc(sizeof(int)); (*intPtr) = 69; printf("%d\n", *intPtr); free(intPtr); Return the Storage with free intPtr The variable still points to storage, which might be used by others 69 The storage is still accessible, but might be taken for other applications (also called a dangling pointer reference)

#include int *intPtr = malloc(sizeof(int)); (*intPtr) = 69; printf("%d\n", *intPtr); free(intPtr); intPtr = NULL; Reset the Pointer to null 0 intPtr The variable now has no dangling pointer 69 Clean up by setting the pointer to NULL or to other storage

#include int *intPtr = malloc(sizeof(int)); (*intPtr) = 69; printf("%d\n", *intPtr); intPtr = NULL; Be Careful of Memory Leaks! 0 intPtr 69 In this case, the storage cannot be accessed by the program, or by the heap manager, and will eventually result in heap underflow! Always free your own storage!

Nodes and Linked Structures datanextdatanext 2 head size Could be a linked stack How do we represent a node in C?

The C struct A struct is a data type that includes one or more named data fields Good for containing data of different types Like classes in Python or Java, but without the methods

struct point{ int x, y; } p1, p2; Declare a Type and Two Variables p1 Storage is automatically allocated when variables are declared x x y p2 y

struct point{ int x, y; } p1, p2; p1.x = 44; p1.y = 55; Initialize the Fields of p1 p1 The field selector (. ) accesses a field for reference or assignment x x y p2 y

struct point{ int x, y; } p1, p2; p1.x = 44; p1.y = 55; p2 = p1; Copy p1 to p2 55 p1 Unlike arrays, the contents of an entire struct can be assigned to another one 44 x x y p2 y

struct point{ int x, y; }; struct point p1, p2; p1.x = 44; p1.y = 55; p2 = p1; Variation 55 p1 Can declare the type, then the variables later 44 x x y p2 y

typedef struct point{ int x, y; } point; point p1, p2; p1.x = 44; p1.y = 55; p2 = p1; Create a Synonym with typedef 55 p1 This synonym happens to be the same name as the name of the struct 44 x x y p2 y

typedef struct node{ int data; struct node *next; } node; typedef node* nodePtr; Declare a Node Type No storage yet, because no variables have been declared

typedef struct node{ int data; struct node *next; } node; typedef node* nodePtr; nodePtr ptr; Declare a Pointer Variable to a Node ptr ptr contains garbage

typedef struct node{ int data; struct node *next; } node; typedef node* nodePtr; nodePtr ptr = malloc(sizeof(node)); Initialize It to a New Node ptr malloc allocates storage for the entire node

typedef struct node{ int data; struct node *next; } node; typedef node* nodePtr; nodePtr ptr = malloc(sizeof(node)); ptr->data = 69; ptr->next = NULL; Initialize the Node’s Contents ptr The -> operator combines * (dereference) and. (field selection) 69

typedef struct node{ int data; struct node *next; } node; typedef node* nodePtr; nodePtr getNode(int data, nodePtr next){; nodePtr ptr = malloc(sizeof(node)); ptr->data = data; ptr->next = next; return ptr; } Define a Helper Function getNode This function creates a new node, initializes its contents, and returns a pointer to it

typedef struct node{ int data; struct node *next; } node; typedef node* nodePtr; nodePtr getNode(int data, nodePtr next){; nodePtr ptr = malloc(sizeof(node)); ptr->data = data; ptr->next = next; return ptr; } int i; nodePtr head = NULL; for (i = 1; i <= 3; i++) head = getNode(i, head); Create a Linked Structure! 31 head 2

typedef struct node{ int data; struct node *next; } node; typedef node* nodePtr; typedef struct linkedStack{ int size; nodePtr top; } linkedStack; linkedStack newStack(); void push(linkedStack *stk, int data); int pop(linkedStack *stk); int size(linkedStack stk); The Header File for a Linked Stack

linkedStack newStack(){ linkedStack stk; stk.top = NULL; stk.size = 0; return stk; } void push(linkedStack *stk, int data){ stk->top = getNode(data, stk->top); stk->size = stk->size + 1; } int pop(linkedStack *stk){ int data = stk->top->data; nodePtr garbage = stk->top; stk->top = stk->top->next; free(garbage); stk->size = stk->size - 1; return data; } int size(linkedStack stk){ return stk.size; } The Implementation

#include #include "stack.h" int main(){ linkedStack stk = newStack(); int i; for (i = 1; i <= 5; i++) push(&stk, i); printf("The stack has %d elements\n", size(stk)); while (size(stk) > 0) printf("Popping %d\n", pop(&stk)); printf("The stack has %d elements\n", size(stk)); } Using the Linked Stack