Computer Organization and Assembly Language C/C++ Pointers and Memory Allocation.

Slides:



Advertisements
Similar presentations
Malloc Recitation By sseshadr. Agenda Macros in C Pointer declarations Casting and Pointer Arithmetic Malloc.
Advertisements

An introduction to pointers in c
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
Programming and Data Structure
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.
Names and Bindings.
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 CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Malloc Recitation Section K (Kevin Su) November 5 th, 2012.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
CIS 101: Computer Programming and Problem Solving Lecture 8 Usman Roshan Department of Computer Science NJIT.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
Pointers. 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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Linked Lists Chained nodes of information create what are called linked lists, with each node providing a link to the next node. A useful feature of linked.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
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 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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
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.
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.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers. The structure of memory Computer memory is a linear sequence of addressable locations Addresses are numbered starting at zero In personal computers,
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
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.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Computer Graphics 3 Lecture 1: Introduction to C/C++ Programming Benjamin Mora 1 University of Wales Swansea Pr. Min Chen Dr. Benjamin Mora.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
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.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
1 Compiler Construction Run-time Environments,. 2 Run-Time Environments (Chapter 7) Continued: Access to No-local Names.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Dynamic Allocation in C
EGR 2261 Unit 11 Pointers and Dynamic Variables
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers and Memory Overview
Objectives You should be able to describe: Addresses and Pointers
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Computer Organization and Assembly Language C/C++ Pointers and Memory Allocation

C/C++ Tidbits C has a standard syntax but types may be implementation dependent Attempts have been made to make types explicit longint, int32, int64, uint, ulong, etc. C soon adopted linking model Code compiles to.obj,.lib.lib,.obj links to.com,.exe References can be made to routines/data not in the current code 2

C/C++ Tidbits Many C implementations allow inline assembly Finer control of code optimization Hardware level interfacing – bypass the OS Not platform independent! Headers define implementation details Different libraries may use different type definitions for the same thing Organization is essential Even so, things quickly get complex 3

Computer Memory Memory 8-bits (byte) wide Organized as a numbered list Range depends on hardware (0 to ???) Addresses can be manipulated just like other integers They can be added, subtracted, etc. They can also be stored in memory 4

Computer Memory Are the contents at 0FFDh an address or data? If it is data, it can be interpreted many ways – up to the programmer If it is an address, it points to the data in 1003h. In this example, addresses are 2 bytes long. 5 … 0FFDh10h 0FFEh03h 0FFFh 1000h 1001h 1002h 1003hC2h 1004hFFh 1005h57h 1006h9Ah …

Computer Memory Most compilers hide the details from you by substituting addresses for symbolic names long int mynum; With static naming, the compiler decides the storage ahead of time and makes the appropriate substitutions. mynum = 1003h to 1006h 6 … 0FFDh10h 0FFEh03h 0FFFh 1000h 1001h 1002h 1003hC2h 1004hFFh 1005h57h 1006h9Ah …

Computer Memory If the variable is dynamic, the compiler often creates a pointer. The pointer is null until the variable is actually created at run-time. You still write the code the same; the compiler handles all substitutions. mynum = 0FFDh -> 1003h 7 … 0FFDh10h 0FFEh03h 0FFFh 1000h 1001h 1002h 1003hC2h 1004hFFh 1005h57h 1006h9Ah …

Computer Memory So why worry about pointers? Efficiency Compiler writing Machine language Pointers are powerful but dangerous Can point to random memory, even program memory Can sometimes point outside allowable memory 8

Computer Memory Some terms: Reference: address stored in memory (1003h) Pointer: variable containing a reference (mynum = 0FFDh) Referenced value: data at an address stored in a pointer (C2FF579Ah) 9 … 0FFDh10h 0FFEh03h 0FFFh 1000h 1001h 1002h 1003hC2h 1004hFFh 1005h57h 1006h9Ah …

C/C++ POINTERS 10

C/C++ Pointers C language handles symbolic names for you But it also allows you to specifically use pointers This is why C/C++ is considered both powerful and dangerous Before we delve into why pointers in C/C++ are useful, let’s learn how to use them… 11

C/C++ Pointers In C/C++ you must declare a variable before you can use it. uint mynum1; <- creates an unsigned byte integer uint* mynum2; <- creates a pointer to a uint The compiler allocates 1 byte for mynum1 and assigns the address as a substitution for mynum1 The compiler allocates 4 bytes for mynum2 but nothing for the unsigned integer 12

C/C++ Pointers mynum1 contains a byte value. mynum2 contains a 2-byte address. At this point all the memory is empty. We say mynum2 = null. 13 … mynum10FFDh?? mynum20FFEh?? V0FFFh?? loopcnt1000h?? sum1001h?? msg11002h?? 1003h?? 1004h?? 1005h?? 1006h?? …

C/C++ Pointers We can go ahead and use our variables. mynum1 = 2; <- puts 02h at mynum1 mynum2 = 15h; <- puts 0015h at mynum2 0015h is now a reference for mynum2 We’d better hope that’s a good address Maybe it’s better to let the compiler help us 14

C/C++ Pointers Method 1: use an existing variable. If we have a variable already allocated, we can get and use its address. mynum2 = &mynum1; The ampersand is shorthand for ‘address of’ Now mynum2 points to the value of mynum1; that is, mynum2 contains 0FFDh. 15

C/C++ Pointers Method 2: explicitly allocate memory. We can allocate new memory dynamically by using malloc() (new or new[] for C++). mynum2 = malloc(1); malloc or new returns the address of the new memory, which is put into mynum2. We passed 1 to malloc to tell it to reserve 1 byte for us but could have reserved more. We could also use the sizeof function. 16

C/C++ Pointers Ok, so we have a pointer variable and it has an address. Now what? If we use the variable directly, we only get the address (reference). newvar = mynum2; <- newvar now holds the address If we want the referenced value, we have to dereference the pointer. newvar = *mynum2; <- newvar now holds the ref value The asterisk means ‘point to’ the address in mynum2 17

C/C++ Pointers We can also assign directly to the reference value Remember, assigning to the pointer changes the address. mynum2 = 25; < -Oops, we just pointed to 0025h; But using the asterisk does what we want. *mynum2 = 25; <- now the reference value is 25 Read it as ‘point to the address in mynum2 and change it to 25’ 18

C/C++ Pointers Now we can mention Method 3: array declarations Array declarations automatically allocate memory char myarray[5]; <- allocates 5 bytes for the array The variable is actually a pointer to the first element of the array. *myarray = 5;// sets the first array value to 5 myarray[0] =5;// same thing 19

C/C++ Pointers Remember, we can do math on pointer values The bracketed number just adds an offset to the beginning of the array. *(myarray + 3) = 5;// sets the third array value to 5 myarray[3] =5;// same thing The bracket notation is safer, especially if you go past the array bounds You can’t replace the asterisk with a [offset] unless you’ve declared an array; otherwise the compiler will complain. 20

MEMORY ALLOCATION 21

Memory Allocation Remember, allocate memory using malloc or new You can allocate as much as you want The sizeof() function will return the size, in bytes, of any type you pass it – including types you’ve defined You can do math inside the function parens: Byte mystring[25]; //25 byte strings malloc(40 * sizeof(*mystring)); // allocate 1000 bytes Beware of allocating pointers, though malloc(40 * sizeof(mystring));// allocate 80 bytes 22

Memory Allocation Variables allocated for you will also be automatically deallocated You must, on the other hand, deallocate anything you allocated explicitly. free() is the command to deallocate (delete or delete[] in C++): free( mynum2); Timing is important Too soon and the data isn’t there when you need it Too late and you could run out of space 23

POINTER USAGE 24

Pointer Usage Again, why pointers? Array Efficiency Lookup vs. Addition vs. Inc. Assembly has no built-in facility C/C++ pointers can point to anything Linked lists Arrays of pointers Function pointers 25

Pointer Usage Non-homogenous arrays Index math can’t work But pointers are all same size, so array of pointers can be indexed and still point to variable objects (myvartype*) myarray[25]; // array of 25 pointers myarray[15] points to the 15 th pointer *myarray[15] points to the 15 th object 26

Pointer Usage Non-homogenous arrays (cont.) You have to keep track of the type of data but you can allocate each pointer individually myarray[12] = malloc(sizeof(mytype1)); myarray[13] = malloc(sizeof(mytype2)); Caution: mixing up types could lead to trouble: mytype2 *newvar = myarray[12]; // !!! Works (pointer = pointer) but … The types pointed to are different and even if size is the same, data fields may not match 27

Structs 28

Structs Structs are mentioned here because they introduce a potentially confusing pointer notation. Structs are generally an aggregation of different data types into a single record. struct student{ char *firstname; char *lastname; uint age; float average; }; 29

Structs Now we can create a pointer to the struct type: struct student *studentptr; Next we allocate the storage (note that the name strings are not allocated): studentptr = malloc(sizeof(student)); Now we can access fields in studentptr in 2 ways: (*studentptr).age = 22; studentptr->age = 22; 30

Structs Think about: studentptr->firstname = “Eric”; or (*studentptr).firstname = “Eric”; Nesting levels of pointers, whether in structs or normal types, can lead to confusion As in algebra with nested parenthesis, it’s best to simplify where possible. With programming, that means the use of intermediate variables: char *tempfirstname = &(studentptr->firstname); *tempfirstname = “Eric”; 31

END OF SECTION 32