Programming in C Advanced Pointers. Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

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.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
1 Memory Allocation Professor Jennifer Rexford COS 217.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
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:
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{
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
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 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Programming in C Pointer Basics.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
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.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
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.
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.
Dynamic memory allocation and Pointers Lecture 4.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
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.
 Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
CNG 140 C Programming (Lecture set 12) Spring Chapter 13 Dynamic Data Structures.
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.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
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.
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.
Programming in C Advanced Pointers.
Stack and Heap Memory Stack resident variables include:
CSCI206 - Computer Organization & Programming
Lecture 6 C++ Programming
Programming in C Pointer Basics.
Memory Allocation CS 217.
Programming in C Pointer Basics.
EECE.2160 ECE Application Programming
Programming in C Pointer Basics.
C Programming Lecture-8 Pointers and Memory Management
Programming in C Pointer Basics.
Programming in C Advanced Pointers.
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Presentation transcript:

Programming in C Advanced Pointers

Pointers to Pointers Since a pointer is a variable type, a pointer may point to another pointer.Since a pointer is a variable type, a pointer may point to another pointer. Consider the following declarationsConsider the following declarations int age = 42;/* an int */ int *pAge = &age;/* a pointer to an int */ int **ppAge = &pAge;/* a pointer to a pointer to an int */ Draw a memory picture of these variable and their relationshipsDraw a memory picture of these variable and their relationships What type and what value do each of the following represent?What type and what value do each of the following represent? –age, pAge, ppAge, *pAge, *ppAge, **ppAge

pointers2pointer.c int main ( ) { /* a double, a pointer to double, ** and a pointer to a pointer to a double */ double gpa = 3.25, *pgpa, **ppgpa; /* make pgpa point to the gpa */ pgpa = &gpa; /* make ppgpa point to pgpa (which points to gpa) */ ppgpa = &pgpa; /* all of these print 3.25 */ printf( "%0.2f, %0.2f, %0.2f", gpa, *pgpa, **ppgpa); return 0; }

Pointers to struct /* define a struct for related student data */ typedef struct student { char name[50]; char major [20]; double gpa; } STUDENT; STUDENT bob = {"Bob Smith", "Math", 3.77}; STUDENT sally = {"Sally", "CSEE", 4.0}; STUDENT *pStudent; /* pStudent is a "pointer to struct student" */ /* make pStudent point to bob */ pStudent = &bob; /* use -> to access the members */ printf ("Bob's name: %s\n", pStudent->name); printf ("Bob's gpa : %f\n", pStudent->gpa); /* make pStudent point to sally */ pStudent = &sally; printf ("Sally's name: %s\n", pStudent->name); printf ("Sally's gpa: %f\n", pStudent->gpa);

Pointer in a struct The data member of a can be any data type, including pointer. The person now has a pointer to the name. The data member of a struct can be any data type, including pointer. The person struct now has a pointer to the name struct. #define FNSIZE 50 #define LNSIZE 40 typedef struct name { char first[ FNSIZE + 1 ]; char last [ LNSIZE + 1]; } NAME; typedef struct person { NAME *pName; int age; double gpa; } PERSON;

Pointer in a struct (2) Given the declarations below, how do we access bob’s name, last name, and first name? Draw a picture of memory represented by these declarations NAME bobsName = {“Bob”, “Smith”}; PERSON bob; bob.age = 42; bob.gpa = 3.4; bob.pName = &bobsName;

Self-referencing structs Powerful data structures can be created when a data member of a is a of the same kind.Powerful data structures can be created when a data member of a struct is a pointer to a struct of the same kind. The simple example on the next slide illustrates the technique.The simple example on the next slide illustrates the technique.

teammates.c typedef struct player { char name[20]; struct player *teammate;/* can’t use TEAMMATE yet */ } TEAMMATE; TEAMMATE *team, bob, harry, john; team = &bob;/* first player */ strcpy(bob.name, “bob”); bob.teammate = &harry;/* next teammate */ strcpy(harry.name, “harry”); harry.teammate = &john;/* next teammate */ strcpy(john.name, “bill”); john.teammate = NULL:/* last teammate */

teammates.c (cont’d) /* typical code to print a (linked) list */ /* follow the teammate pointers until ** NULL is encountered */ TEAMMATE *t = team; while (t != NULL) { printf(“%s\n”, t->name); t = t->teammate; }

Dynamic Memory C allows us to allocate memory in which to store data during program execution.C allows us to allocate memory in which to store data during program execution. Dynamic memory has two primary applicationsDynamic memory has two primary applications –Dynamically allocating an array (based on some user input) Better than guessing and defining the array size in our code since it can’t be changed –Dynamically allocating structs to hold data in some predetermined arrangement (a data stucture) Allows an “infinite” amount of data to be stored

Dynamic Memory Functions These functions are used to allocate and free dynamically allocated heap memory and are part of the standard C library. To use these functions, include. void *malloc( size_t nrBytes ); –Returns a pointer to dynamically allocated memory on the heap of size nrBytes, or NULL if the request cannot be satisfied. The memory is uninitialized. void *calloc( int nrElements, size_t nrBytes ); –Same as malloc( ), but the memory is initialized to zero void *realloc( void *p, size_t nrBytes); –Changes the size of the memory pointed to by p to nrBytes. The contents will be unchanged up to the minimum of the old and new size. If the new size is larger, the new space is uninitialized. Returns a pointer to the new memory, or NULL if request cannot be satisfied in which case *p is unchanged. void free( void *p ) –Deallocates the memory pointed to by p which must point to memory previously allocated by calling one of the functions above. Does nothing if p is NULL.

void* and size_t The type is C’s generic pointer. It may point to any kind of variable, but may not be dereferenced. Any other pointer type may be converted to and back again without loss of information. is often used as parameter types to, and return types from, library functions.The void* type is C’s generic pointer. It may point to any kind of variable, but may not be dereferenced. Any other pointer type may be converted to void* and back again without loss of information. void* is often used as parameter types to, and return types from, library functions. is an unsigned integral type that should be used (rather than ) when expressing “the size of something” (e.g. an int, array, string, or struct). It too is often used as a parameter to, or return type from, library functions. By definition, is the type that is returned from the operator.size_t is an unsigned integral type that should be used (rather than int ) when expressing “the size of something” (e.g. an int, array, string, or struct). It too is often used as a parameter to, or return type from, library functions. By definition, size_t is the type that is returned from the sizeof( ) operator.

malloc( ) for arrays returns a pointer to uninitialized memory.malloc( ) returns a void pointer to uninitialized memory. Good programming practice is to cast the to the appropriate pointer type.Good programming practice is to cast the void* to the appropriate pointer type. Note the use of for portable coding.Note the use of sizeof( ) for portable coding. As we’ve seen, the pointer can be used as an array name.As we’ve seen, the pointer can be used as an array name. int *p = (int *)malloc( 42 * sizeof(int)); for (k = 0; k < 42; k++) p[ k ] = k; for (k = 0; k < 42; k++) printf(“%d\n”, p[ k ]; Exercise: rewrite this code using as a pointer rather than an array name Exercise: rewrite this code using p as a pointer rather than an array name

calloc( ) for arrays returns a pointer to memory that is initialized to zero.calloc( ) returns a void pointer to memory that is initialized to zero. Note that the parameters to are different than the parameters forNote that the parameters to calloc( ) are different than the parameters for malloc( ) int *p = (int *)calloc( 42, sizeof(int)); for (k = 0; k < 42; k++) printf(“%d\n”, p[k]); Exercise: rewrite this code using as a pointer rather than an array name Exercise: rewrite this code using p as a pointer rather than an array name

realloc( ) changes the size of a dynamically allocated memory previously created by or and returns a pointer to the new memoryrealloc( ) changes the size of a dynamically allocated memory previously created by malloc( ) or calloc( ) and returns a void pointer to the new memory The contents will be unchanged up to the minimum of the old and new size. If the new size is larger, the new space is uninitialized.The contents will be unchanged up to the minimum of the old and new size. If the new size is larger, the new space is uninitialized. int *p = (int *)malloc( 42 * sizeof(int)); for (k = 0; k < 42; k++) p[ k ] = k; p = (int *_)realloc( p, 99 * sizeof(int)); for (k = 0; k < 99; k++) p[ k ] = k * 2; for (k = 0; k < 99; k++) printf(“%d\n”, p[k]);

Testing the returned pointer and all return if unable to fulfill the requested memory allocation.malloc( ), calloc( ) and realloc( ) all return NULL if unable to fulfill the requested memory allocation. Good programming practice dictates that the pointer returned should be validatedGood programming practice dictates that the pointer returned should be validated char *cp = malloc( 22 * sizeof( char ) ); if (cp == NULL) { /* handle the error */ }

free( ) is used to return dynamically allocated memory back to the heap to be reused by later calls to orfree( ) is used to return dynamically allocated memory back to the heap to be reused by later calls to malloc( ), calloc( ) or realloc( ) The parameter to must be a pointer previously returned by one of orThe parameter to free( ) must be a pointer previously returned by one of malloc(), calloc() or realloc( ) Freeing a pointer has no effectFreeing a NULL pointer has no effect Failure to free memory is known as a “memory leak” and may lead to program crash when no more heap memory is availableFailure to free memory is known as a “memory leak” and may lead to program crash when no more heap memory is available int *p = (int *)calloc( 42, sizeof(int)); /* code that uses p */ free( p );

Dynamic Memory for structs In JAVA public class Person { public int age; public double gpa; } // memory allocation Person bob = new Person( ); bob.age = 42; bob.gpa = 3.5; // bob is eventually freed // by garbage collector In C typedef struct person { char name[ 51 ]; int age; double gpa; /* memory allocation */ PERSON *pbob = (PERSON *)malloc(sizeof(PERSON)); pbob->age = 42; pbob->gpa = 3.5; strcpy( pbob->name, “bob”);... /* explicitly freeing the memory */ free( pbob );

Dynamic Teammates typedef struct player { char name[20]; struct player *teammate; } PLAYER; PLAYER *getPlayer( ) { char *name = askUserForPlayerName( ); PLAYER *p = (PLAYER *)malloc(sizeof(PLAYER)); strcpy( p->name, name ); p->teammate = NULL; return p; }

Dynamic Teammates (2) int main ( ) { int nrPlayers, count = 0; PLAYER *pPlayer, *pTeam = NULL; nrPlayers = askUserForNumberOfPlayers( ); while (count < nrPlayers) { pPlayer = getPlayer( ); pPlayer->teammate = pTeam; pTeam = pPlayer; ++count; } /* do other stuff with the PLAYERs */ /* Exercise -- write code to free ALL the PLAYERs */ return 0; }