Pointers in C Computer Organization I 1 August 2009 ©2006-09 McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.

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
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
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.
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.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
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.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
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.
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.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
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.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
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
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
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,
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers. The structure of memory Computer memory is a linear sequence of addressable locations Addresses are numbered starting at zero In personal computers,
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
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.
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.
Dynamic memory allocation and Pointers Lecture 4.
Runtime Stack Computer Organization I 1 November 2009 © McQuain, Feng & Ribbens MIPS Memory Organization In addition to memory for static.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers *, &, array similarities, functions, sizeof.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
© 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.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
P OINTERS A pointer is an address All data is stored in memory in some location that is indexed with an address Can refer to variables by name or by memory.
CSE 351 Dynamic Memory Allocation 1. Dynamic Memory Dynamic memory is memory that is “requested” at run- time Solves two fundamental dilemmas: How can.
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 Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
More Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Allocating Arrays Dynamically You allocate an array by.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
C Part 2 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens The Three Attributes of an Identifier Identifiers have three essential.
Dynamic Allocation in C
Stack and Heap Memory Stack resident variables include:
The Three Attributes of an Identifier
Memory and Addresses Memory is just a sequence of byte-sized storage devices. The bytes are assigned numeric addresses, starting with zero, just like the.
CSC 253 Lecture 8.
CSC 253 Lecture 8.
Pointers, Dynamic Data, and Reference Types
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Dynamic Allocation in C
Dynamic Memory – A Review
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized storage devices. The bytes are assigned numeric addresses, starting with zero, just like the indexing of the cells of an array. It is the job of the operating system (OS) to: -manage the allocation of memory to processes -keep track of what particular addresses each process is allowed to access, and how -reserve portions of memory exclusively for use by the OS -enforce protection of the memory space of each process, and of the OS itself -do all this as efficiently as possible

Pointers in C Computer Organization I 2 August 2009 © McQuain, Feng & Ribbens Run-time Stack When a function call occurs, storage space must be available for: -parameters that are passed to the function -local variables with automatic duration declared within the function -the return value, if any This is accomplished by creating a data object, called an activation record, whenever a function call takes place. The activation record contains storage space for all of the items mentioned above, and perhaps more. When a function terminates, the corresponding activation record is destroyed. It is natural to organize these activation records on a stack. Why? Each process has such a stack, maintained by the system as the process runs. The process cannot directly manipulate the stack, but it is allowed to access those portions of it that correspond to its local variables.

Pointers in C Computer Organization I 3 August 2009 © McQuain, Feng & Ribbens Run-time Stack Start Value... int nextPrimeAfter(int Start) { int Value = Start + 1; while ( !isPrime( Value ) ) { ++Value; } return Value; } main() nextPrimeAfter() int main( ) {... Prime = nextPrimeAfter( Prime );... } main()

Pointers in C Computer Organization I 4 August 2009 © McQuain, Feng & Ribbens Heap Processes also often need to create data objects "on the fly" as they execute. This is accomplished by making a call to the OS requesting that the necessary amount of memory be allocated to the process. The OS responds by either: -returning the address of the first byte of a chunk of memory allocated to the process -denying the request Dynamically-allocated memory is allocated from a reserved region of system memory called the heap.

Pointers in C Computer Organization I 5 August 2009 © McQuain, Feng & Ribbens sizeof() operator sizeof( typename ) returns the size in bytes of an object of type typename sizeof( char ) guaranteed to be 1 sizeof( other ) may vary from system to system int A[SZ]; sizeof( A ) returns actual size of array in bytes; i.e., number of cells times the size of a cell

Pointers in C Computer Organization I 6 August 2009 © McQuain, Feng & Ribbens Pointer Concepts and Syntax pointera variable whose value is a memory address pointeea value in memory whose address is stored in a pointer; we say the pointee is the target of the pointer Since memory addresses are essentially just integer values, pointers are the same width as integers. A pointer has a type, which is related to the type of its target. Pointer types are simple; there is no automatic initialization. A pointer may or may not have a target. Given a pointer that has a target, the target may be accessed by dereferencing the pointer. A pointee may be the target of more than one pointer at the same time. Pointers may be assigned and compared for equality, using the usual operators. Pointers may also be manipulated by incrementing and decrementing, although doing so is only safe under precisely-defined circumstances. By convention, pointers without targets should be set to 0 (or NULL ).

Pointers in C Computer Organization I 7 August 2009 © McQuain, Feng & Ribbens Basic Pointer Syntax Declarations: int x = 42, y = 99; char s[] = "Pointers are good for you!"; int* p1; // declaration of pointer-to-int char *p2; // pointer-to-char p1 = &x; // p1 points to x p2 = s; // p2 points to s Setting targets: &X returns the address of the object X ; the address-of operator *P names the target of the pointer P ; the dereference operator

Pointers in C Computer Organization I 8 August 2009 © McQuain, Feng & Ribbens Basic Pointer Syntax *p1 = 23; // now x == 23 printf("%d", p1); // prints value of p1 printf("%d", *p1); // prints target of p1 printf("%s", p2); // prints char "string" p1 = &y; // now p1 points to y p1 = NULL; // now p1 has no target, AND // we can check that Dereferencing:

Pointers in C Computer Organization I 9 August 2009 © McQuain, Feng & Ribbens Dynamic Allocation in C The previous example involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically, as the program executes. In C, this is accomplished via the Std Library function malloc() and friends: malloc() allocates a block of uninitialized memory; returns the address calloc() allocates a block of memory and clears it; returns the address realloc() resizes a previously allocated block of memory; returns the address int *A = malloc( 1000 * sizeof(int) ); char *B = malloc( 5000 ); uint64_t Size = 100; double *C = malloc( Size * sizeof(double) );

Pointers in C Computer Organization I 10 August 2009 © McQuain, Feng & Ribbens Dynamic Allocation Failure It is always possible that an allocation request will be denied; in that case, malloc() and friends will return NULL. A deadly sin is to not check the return value from malloc() to be sure it isn't NULL : Without the check of A, the subsequent code will probably lead to a runtime error (unless there was no need for the array). int *A = malloc( 1000 * sizeof(int) ); if ( A == NULL ) { printf("Failed to allocate space for A!\n"); exit(1); }

Pointers in C Computer Organization I 11 August 2009 © McQuain, Feng & Ribbens Deallocation in C Deallocation is accomplished by using the Std Library function free() : One of the most glaring differences between Java and C is how memory deallocation is accomplished. In C, we have static allocations, local or automatic allocations, and dynamic allocations. The first two are of no particular interest here. Everything that your C program allocates dynamically must eventually be deallocated. The responsibility is yours. Failure to deallocate memory in a timely but safe manner is one of the most common programming mistakes in most languages, including C. free() does not reset the value of the pointer on which it is invoked! int *A = malloc( 1000 * sizeof(int) );... free(A);

Pointers in C Computer Organization I 12 August 2009 © McQuain, Feng & Ribbens C free() It's important to understand just what free() does (and does not do). First, free() can only be applied to a pointer storing the address of a target that was allocated by calling malloc() and friends. Second, free() can only be applied to a pointer whose a target that has not already been deallocated. Third, when free() is invoked on a pointer, the pointer is not automatically reset to NULL. Fourth, free() causes the deallocation of the target of the pointer, not the deallocation of the pointer itself. You don't free a pointer, you free its target.

Pointers in C Computer Organization I 13 August 2009 © McQuain, Feng & Ribbens Dangling Pointers and Aliases The most common source of errors with direct pointer use is to dereference a pointer that does not have a valid target: int *A; *A = 42; // A never had a target int *A = NULL; if ( A != NULL ) // used correctly, NULL *A = 42; // lets us check int *A = malloc( sizeof(int) ); // A has a target int *B = A; // B shares it; alias free(A); // neither has a target *B = 42; // ERROR