MORE POINTERS Plus: Memory Allocation Heap versus Stack.

Slides:



Advertisements
Similar presentations
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
Advertisements

Dynamic memory allocation
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
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.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Programming Languages and Paradigms The C Programming Language.
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
Pointers Applications
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Outline Midterm results Static variables Memory model
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
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.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Pointers OVERVIEW.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Dynamic Memory Allocation Suppose we defined the data type: struct custrec.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Introduction to Data Structures Systems Programming Concepts.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
Sudeshna Sarkar, CSE, IIT Kharagpur1 Structure and list processing Lecture
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming malloc, calloc, realloc.
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
5.13 Recursion Recursive functions Functions that call themselves
Lectures linked lists Chapter 6 of textbook
CSCI206 - Computer Organization & Programming
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
EECE.2160 ECE Application Programming
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Presentation transcript:

MORE POINTERS Plus: Memory Allocation Heap versus Stack

Where should we store stuff? What’s wrong with this: char* getString() { char result[80]; …. Some code to put data into result … return result; } Somehow, programs must modify or create data structures that persist in the program regardless of procedure calls… So far the only variables we have seen (except for globals) are declared at the beginning of blocks and are “on the stack” Variables “on the stack” disappear when the block they are declared in is exited or returned from.

The answer is the heap… What is it? –An area of memory distinct from the program stack –Access to it is controlled, not by the compiler, but by specific library procedures: #include malloc(), calloc() reserve blocks of memory for program use free() returns blocks of memory to the heap for reuse

Dynamic Storage Allocation The use of memory in the heap is referred to as “dynamic storage allocation” Arrays, strings, structures may all be stored in memory reserved in the heap area Pointers are used to maintain references to objects allocated in the heap. Objects in the heap may contain references to each other, forming what is known as a “data structure” All objects in the heap are unaffected by actions taking place on the program stack

The malloc Function The most important storage allocation function is named malloc. When called, malloc allocates (reserves) a block of size bytes and returns a pointer to it: void *malloc(size_t size); malloc returns a “generic” pointer that is capable of pointing at an object of any type. malloc’s return value can be stored in a variable of any pointer type: int *pi; pi = malloc(sizeof(int)); … or better yet… pi = (int *) malloc(sizeof(int)); For portability, it is best to use sizeof when calling malloc, you don’t want to have to remember..

malloc malloc reserves a portion of the heap, and gives you a pointer to it to use as you see fit. It will not re-allocate that portion of heap memory until you “free” it. –The memory reserved is not initiallized –Be careful not to access the memory below or above what is allocated… Stay in bounds! calloc() is a closely related function

The Null Pointer Since NULL is equivalent to 0, it tests false in if, while, do, and for statements: int *p; … if (p) … /* true if p is not NULL */ It is illegal to apply the indirection operator to a null pointer: p = NULL; i = *p; /* illegal */

Dynamically Allocated Strings malloc is can be used to dynamically allocate space for strings. char *result; result = malloc(strlen(s1) + strlen(s2) + 1); strcpy(result, s1); strcat(result, s2); return result; Now, the string returned is in the heap and not on the stack. A pointer to it can be passed around and stored without concern about its memory location. Warning: When using malloc to allocate space for a string, don’t forget to include room for the null character.

Dynamically Allocated Arrays An array can be dynamically allocated by a call to the calloc function. calloc() is similar to malloc, but allocates space for an array with n elements, each of which is size bytes long: void *calloc(int n, int size); calloc will allocate n*size bytes, passing back a pointer to the beginning of the memory block it reserved. calloc does one thing that malloc does not do: it will set every byte it allocates to zero, clearing the elements so you don’t have to.

Dynamically Allocated Arrays Example: int *a, size, i; printf("Enter array size: "); scanf("%d", &size); a = (int *) calloc(size, sizeof(int)); printf("Enter array elements: "); for (i = 0; i < size; i++) scanf("%d", &a[i]); Warning: A program that uses malloc or calloc must include the following header file: #include

The free Function When a block of memory obtained by calling malloc or calloc is no longer referenced by a pointer, it is said to be garbage. In the following example, the memory pointed to by p becomes garbage when p is assigned a new value: int *p, *q; p = malloc(sizeof(int)); q = malloc(sizeof(int)); p = q; Garbage should be avoided; we need to “recycle” memory instead. Failure to do so causes “memory leaks” which will ultimately cause a program to fail when its heap is full (of garbage).

The free Function When a block of memory is no longer needed, it can be released back to the heap by calling the free function: int *p, *q; p = malloc(sizeof(int)); q = malloc(sizeof(int)); free(p); p = q; Warning: Watch for “dangling pointers” left behind after a call to free: int *p, *q; p = malloc(sizeof(int)); q = p; free(p); *q = 0; /* error, writing to freed heap area */

Linked Lists Dynamic storage allocation is useful for building lists, trees, graphs, and other linked structures. A linked structure consists of a collection of nodes. Each node contains one or more pointers to other nodes. In C, a node is represented by a struct. The simplest linked structure is the linked list, which consists of a chain of nodes, with each node pointing to the next node in the chain. A node in a linked list might have the following definition: struct node { int data; struct node *next; }; The use of a structure name is mandatory, since the node structure contains a reference to itself.

Linked Lists An ordinary pointer variable points to the first node in the list. To indicate that the list is empty, the variable can be assigned NULL: struct node *first = NULL; Nodes could be allocated from the heap and added as a linked list: struct node* addNode(struct node* previous) { struct node* n = (struct node*) malloc(sizeof(struct node)); n->data = … initialize data … n->next = NULL; previous->next = n; return n; } addNode(first);

The Right Arrow Operator Nodes can be created by calling malloc: struct node *temp; temp = (struct node*) malloc(sizeof(struct node)); The. operator could be used to select a data member in the node pointed to by temp: (*temp).data = n; Because pointers often point to structures, C provides a special notation (the right arrow selection operator) for selecting members of these structures: temp->data = n;

Example: Inserting into a Linked List The following statements will create a node containing n, then insert it at the beginning of the list pointed to by first: struct node *temp; temp = malloc(sizeof(struct node)); temp->data = n; temp->next = first; first = temp;

Example: Inserting into a Linked List The following example creates a linked list containing numbers entered by the user: struct node *first = NULL, *temp; int n; printf("Enter a series of numbers: "); scanf("%d", &n); while (n != 0) { temp = malloc(sizeof(struct node)); temp->data = n; temp->next = first; first = temp; scanf("%d", &n); } The numbers will appear in the list in the reverse of the order in which they were entered.

Example: Searching a Linked List The following statement searches a list for an integer n: for (temp = first; temp != NULL; temp = temp->next){ if (temp->data == n){ … /* found n */ } /* same thing written as a while loop */ temp = first; while (temp != NULL) { if (temp->data == n) { … /* found n */ } temp = temp->next; }

Deleting from a Linked List The following statements will delete the first node containing n from the list pointed to by first, assuming that n is present in the list: struct node *p, *q; p = first; q = NULL; while (p != NULL) { if (p->data == n) { if (q) q->next = p->next; else first = p->next; free(p); break; } q = p; p = p->next; }

Strings on the Heap When you do something like this… char* getAString() { char s[80]; scanf( “ %s ”,s); return s; } String “s” is on the stack, and disappears when the function returns, leaving the return value pointing at who-knows-what. ***** This is a BAD THING! *****

Strings on the Heap Instead, allocate strings from the heap… char* getAString() { char* s = (char*) malloc(sizeof(char)*80); scanf( “ %s ”,s); return s; } But there is a better way… Using a library function

Strings on the Heap Use the function “ strdup ”: char* getAString() { char s[80]; scanf( “ %s ”,s); return strdup(s); } strdup() takes a string as a parameter, allocates len(string)+1 bytes from the heap, copies the string into the allocated memory and returns a pointer to the copy (the copy is in the heap, regardless of where the original string was).