references vs. pointers, addresses, pointer arithmetic, pointers & arrays, stack & heap...

75
References, Pointers and Memory References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team http://academy.telerik.com Telerik Software Academy

Upload: wendy-juliana-lee

Post on 01-Jan-2016

247 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

References, Pointers and

MemoryReferences vs. Pointers,

Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory

Learning & Development Teamhttp://academy.telerik.com

Telerik Software Academy

Page 2: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Table of Contents

1. References and their Applications

2. Pointers and Memory

3. Working with Pointers

Referencing & Dereferencing

Pointer arithmetic

4. Pointers vs. References

5. Pointers and Arrays

6. C++ Memory and Storage Types

7. Working with Dynamic and Static Memory

2

Page 3: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

ReferencesVariables aliases, Passing references

to functions

Page 4: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

References A variable indicates a chunk of memory Computer perceives the variable as

that chunk

References are aliases of variables Same type, same memory, different

name

i.e., indicate same chunk of memory as the variable

A reference only represents one variable Through its lifetime

Must be initialized immediately (on declaration)

Page 5: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

References Syntax for defining a reference to a

variable

Reference points to same memory as its variable: Its value is the value

of the variable

Assigning the reference a value will actually assign the variable a value

int v = 5;int &r = v;cout<<r<<endl; //prints 5v = 6;cout<<r<<endl; //prints 6r = 4;cout<<v<<endl; //prints 4cout<<r<<endl; //prints 4

int &r = someVar; //reference to variable named //someVar (already existing)

'&' denotes

a referenc

e

Initialization is

obligatory

Page 6: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Reference BasicsLive Demo

Page 7: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Usage of References References are most used with functions Enable the function to change

parameters

Remove overhead from "sending" parameters

int SomeFunction(int &parameterByReference, ...){ //...}

Page 8: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Usage of References Reference parameters to edit values The function accesses the variable,

not its copy

Variable passed in call to function is affected

void MakePositive(int &number){

if(number < 0){ //this affects the variable in the

callernumber = -number;

}}int main(){

int a = -5;MakePositive(a); //after this line, a is

5}

Page 9: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Usage of References References to avoid overhead

Normal parameters are copied

Copying large objects can take too much time Especially when this happens often

Almost no good reason to copy parameters Any operation done on a copy can be

done on a reference – with the same effect (when reading)

Sending by reference doesn't copy the object, just its reference (which is fast)

Page 10: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Usage of References Example of fast and slow way of sending parameters to a function

Note: this is valid for potentially large objects (a vector can have many elements). Sending primitive types (int, char…) by copy and by reference is almost the same in speed

int GetSum(vector<int> &nums) //fast – only reference is sent{

int sum = 0int size =

nums.size();for(int i=0; i<size;

i++){

sum += nums[i];}return sum;

}

int GetSum(vector<int> nums) //overhead – elements copied{

int sum = 0int size =

nums.size();for(int i=0;

i<size; i++){

sum += nums[i];

}return sum;

}

Page 11: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Usage of References Reference parameters can be a problem OK to send reference instead of the

whole data

But does the function read or edit the data? You can't be sure, especially if you're

using 3rd party code

const references solve this problem

Page 12: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Usage of References const references

Work the same way, but data can only be read

A normal reference can be assigned to a const one

A const reference cannot be assigned to a normal one

i.e. a function cannot make a writeable reference from a const one

int GetSum(const vector<int> &nums){ //this function can't edit nums

int sum = 0int size = nums.size();for(int i=0; i<size; i++){

sum += nums[i];}return sum;

}

Page 13: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Using ReferencesLive Demo

Page 14: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and MemoryRepresenting data in bytes, Variable

addresses, Stack and Dynamic Memory

Page 15: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory Computers work on data, stored in variables

Variables a program has at a given time are in the Random Access Memory (RAM) RAM is just an array of bytes

(software POV)

Each byte in RAM has an address (e.g. 0x000013A1)

Its index in the array, usually as a hex number

Information is described by address and value of the byte(s) at that address

Page 16: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory Early computing days

Programming was moving and editing bytes

From one address to another

No "abstract" operations such as +, -, *, /

The programmer writes everything from scratch

Today, low-level memory is handled through: Data types

Predefined operations (often on hardware level)

E.g. assigning values is copying memory

Page 17: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Variables in Memory Most data types occupy more than one byte Occupied bytes are sequential

E.g. data for a 4-byte int starting at 0x000013A3, also occupies 0x000013A4, 0x000013A5 and 0x000013A6

Address of a variable The address of its first byte

The program can access the next bytes By knowing the size of the data type

Page 18: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Variables in Memory Example of a 4-byte integer in memory at address 0x13A3, with a value of 624 in a Big-endian system

i.e. most-significant byte is leftmost address

Address 0x13A2

0x13A3 0x13A4 0x13A5 0x13A6 0x13A7

Data … 00000000 00000000 00000010 01110000 …

int x = 624;

int x = 624;cout<<&x<<endl; //outputs 0x13A3 //(in the described case)//&x reads as "the address of x"//not the same as reference variables,//returns address of the first byte of x

Page 19: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory Pointers Pointer – special variable, associated with an address in memory Holds the memory address of

another variable

"Points" to another variable

Can point to any byte in memory

Special "null" (0) value – shows the pointer currently holds no variable's address

Two essential operations for using pointers Referencing Dereferencing

Page 20: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory Pointers Referencing – getting a variable's address Variable's address (as a number) is

returned from the variable's identifier

i.e. gets the value of a pointer to the variable

Address 0x13A2

0x13A3 0x13A4 0x13A5 0x13A6 0x13A7

Data … 00000000 00000000 00000010 01110000 …

int x = 624;

Here, referencing x gives 0x13A3 (5027 decimal)Let p be a pointer to xThen, the value of p is 0x13A3 (5027 in decimal)

Page 21: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory Pointers Dereferencing – getting value from an address The variable (the memory data) is

returned from a pointer to that variable

i.e. accesses memory at the address, pointed by the pointer

* Note: we need to know the data type to dereference

Address 0x13A2

0x13A3 0x13A4 0x13A5 0x13A6 0x13A7

Data … 00000000 00000000 00000010 01110000 …

p is a pointer to address 0x13A3

Let us dereference p as a 4-byte integer* xThe data for x is in bytes 0x13A3 to 0x13A6Then the value of x is 624

Page 22: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and Memory Pointers – the common way to access memory

Most programming languages use pointers Some allow full access (like C and

C++)

Some hide pointers objects (C#, JS)

Reference and Dereference operators respectively create and evaluate pointers

Usually pointers can be incremented/decremented i.e. "moved" to neighboring

addresses

Page 23: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Working with Pointers in C++The & and * operators, Pointer values and arithmetic,

const pointers, Building pointers from addresses

Page 24: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Working with Pointers in C++

C++ provides lots of functionality for working with pointers Assigning pointers to variables and

dereferencing

Pointer types – int, char, string, etc.

Basic memory pointers – a.k.a. void pointers

Assigning pointers to arbitrary memory addresses

Incrementing/Decrementing pointers

Casting pointers from one type to another

Page 25: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers in C++ – Creating

Declaring and assigning pointers C++ pointers have types and are

declared as normal variables

A * (asterisk) sign prefix of the variable name denotes a pointer

Typically, assigning values requires a variable's address – which is returned by the & operatorint v = 5;int *vPtr;vPtr = &v; //get the address (pointer to) vcout<<vPtr<<endl; //prints hex address of v

Page 26: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers in C++ – Dereferencing

Getting values from pointers C++ pointers have types

Dereferencing accesses memory as

Dereferencing is done through the * (asterisk) operator, as a prefix to an existing pointer This gives direct read/write access to

the memory

Note: * is used for declaration and dereferencing

int v = 5;int *vPtr = &v; //here, * means create a pointer(*vPtr)++; //here, * means access the pointed memorycout<<*vPtr<<endl; //prints 6

Page 27: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer BasicsLive Demo

Page 28: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer Arithmetics Arithmetic operations on pointers

"Move" a pointer to a neighboring memory cell

Addresses are just numbers

Moving from one address to the next means incrementing/decrementing the pointer

Allowed arithmetic operations on pointers Addition

Subtraction

i.e. move a pointer 1, 2, 3, etc… positions

Page 29: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer Arithmetics Pointer arithmetics work in different ways For different pointer types

E.g. incrementing int* and char* usually works differently

Increment/Decrement depend on data type More precisely, the size of the data

type

Incrementing a pointer of type T by 1 means incrementing the address to which it points to by 1 multiplied by sizeof(T)

Decrementing is analogous

Page 30: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer Arithmetics Example of pointer arithmetics

Suppose the current system uses 1 byte for char, 2 bytes for short and 4 bytes for intchar *charPtr = ...//memory address 0x13A0short *shortPtr = ...//memory address 0x14A0int *intPtr = ...//memory address 0x15A0

charPtr++; shortPtr++; intPtr++;

cout<<charPtr<<", "<<shortPtr<<", "<<intPtr<<endl;//prints 0x13A1, 0x14A2, 0x15A4

Page 31: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer Arithmetics Example explanation

0x13A0 0x13A1 0x13A2 0x13A3 0x13A4

0x14A0 0x14A1 0x14A2 0x14A3 0x14A4

0x15A0 0x15A1 0x15A2 0x15A3 0x15A4

charPtr is 0x13A0, sizeof(char) is 1, 0x13A0 + 1 = 0x13A1

shortPtr is 0x14A0,sizeof(short) is 2, 0x14A0 + 2 = 0x14A2

intPtr is 0x15A0,sizeof(int) is 4, 0x15A0 + 4 = 0x15A4

charPtr

shortPtr

intPtr

0x13A0 + sizeof(char)

0x14A0 + sizeof(short)

0x15A0 + sizeof(int)

Page 32: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer ArithmeticsLive Demo

Page 33: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer Arithmetics A pointer can be incremented/decremented with any value (not just using ++ and --)

The expression p = p + 3 is valid Where p is a pointer

Same rule for increasing by a multiple of type size is enforced

E.g. if p is an int pointer to address 0x15A0 after the expression is evaluated p

points 0x15AC

The same rules apply for subtraction

Page 34: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and const As with references,

values pointed by pointers can be marked const

Unlike references, pointers can change to what they

point Two pointer characteristics that can

be const

Meaning a total of 4 pointer variations

Page 35: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and const Non-constant pointer to non-constant variable Pointed memory can be modified by

pointer

Pointed address can be changed

This is the "normal" pointer, from previous examples

int x = 5; int *xPtr = &x; xPtr++; xPtr--; (*xPtr) = 4;int *otherXPtr = xPtr; //all operations valid

Page 36: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and const Non-constant pointerto constant variable Pointed memory cannot be modified

by pointer

Pointed address can be changedint x = 5;const int *xPtr = &x;xPtr++; xPtr--; (*xPtr) = 4; //error: read-only memoryint *otherXPtr = xPtr; //error: invalid conversion

Page 37: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and const Constant pointerto non-constant variable Pointed memory can be modified by

pointer

Pointed address cannot be changedint x = 5;int * const xPtr = &x;xPtr++; //error: read-only pointerxPtr--; //error: read-only pointer(*xPtr) = 4;int *otherXPtr = xPtr;

cout<<x<<endl;

Page 38: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and const Constant pointerto constant variable Pointed memory cannot be modified

by pointer

Pointed address cannot be changedint x = 5;const int * const xPtr = &x;xPtr++; ///error: read-only pointerxPtr--; ///error: read-only pointer(*xPtr) = 4; ///error: read-only memoryint *otherXPtr = xPtr; ///error: invalid conversion

cout<<x<<endl;

Page 39: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and const Pointers are useful as function parameters

Non-const pointers to non-const variables Passing data to the function for

modification

Traversing and modifying memory (arrays)

Non-const pointers to const variables Efficiently passing large data to a

function Protecting the data from

modification

Much like const references, so most compilers implement const references this way

Page 40: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and const const pointers in general

Useful for storing specific memory locations And using them directly, i.e. no

casting

Especially when working with: Hardware expecting input at a

specific address (i.e. you use const pointer to non-const memory)

Hardware producing output at a specific address (i.e. you use const pointer to const memory)

Page 41: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and constLive Demo

Page 42: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers to Pointers in C++

Pointers are just numbers and have addresses

So you can have pointers to pointers Each pointer "level" is called an

indirection E.g., a pointer to a pointer is a

double indirection

At declaration, one * per each indirection

char x = 'a';char * xPtr = &x;char ** xPtrPtr = &xPtr;

Address 0x13A0 0x14A0 0x15A0

Value 'a' 0x13A0 0x14A0

x * xPtr ** xPtrPtr

Page 43: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers to Pointers in C++

Pointers to pointers have many applications Multidimensional arrays, composite

objects, …

Modifying pointer address by functions i.e. modify where the pointer points,

not the data

void MovePtrToNextZero(int ** pointerAddress){ int value = **pointerAddress; while(value != 0) { (*pointerAddress)++; value = **pointerAddress; }} //Note: an often better (not always applicable) approach //is to return a new pointer, not modify the parameter

Page 44: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers to PointersLive Demo

Page 45: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer to Specific Memory

C++ allows creating pointers to specific memory addresses

E.g. you can make a pointer point to 0x13A0 Regardless of whether or not the

program is allowed to access that memory

Accessing the memory could trigger an access violation (error code 0xC0000005)

Avoid creating pointers in such a way Very unsafe and error-prone

Necessary in some cases (low-level code)

Page 46: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointer to Specific Memory

Initialize pointer to specific memory address Simply provide the address as a

number Hex is the convention, but not

obligatory

And cast it to the desired pointer type

Some argue cast should be reinterpret_cast reinterpret_cast forces cast

(regardless of type)

Also sort of says "Here be dragons!"

int *ptr = (int*)5024;int *otherPtr = reinterpret_cast<int*>(0x13A0);cout << (ptr==otherPtr) << endl; //prints 1cout << ptr << endl; //prints 0x13A0

Page 47: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers in C++ – Void Pointers

Void pointers are a special type of pointer Not associated with a data type

Can point to any variable/byte of memory Useful as a "universal pointer"

Cannot do pointer arithmetic

Cannot modify memory or be dereferenced

Void pointers are useful after casted

int a = 5; char b = 'x'; void *p;p = &a; p = &b;cout << *((char*)p) << endl; //prints 'x'

Page 48: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

C++ Function Pointers Function pointers are special pointers Similar restrictions as void pointers

Typically used to pass functions as parameters

Declaration and calling are similar to normal function declaration and calling With brackets around function name

* before function name, inside the brackets

#include <cmath>...double (*squareRootPtr)(double) = sqrt;cout << (*squareRootPtr)(9) << endl; //prints 3

Page 49: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Function PointersLive Demo

Page 50: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers vs. ReferencesMain Differences, Advantages and

Disadvantages

Page 51: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

References vs. Pointers Pointers are generally more versatile Exist before references (pure C)

A lot of functionality and various types

Low(est)-level memory access

Base for polymorphism in C++ OOP

Harder to read, require a lot of operators

Relatively unsafe and error prone

Page 52: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

References vs. Pointers References are generally tidier and safer High level – act as variables, not

addresses

No special operators except at declaration Easy to initialize, work with and read

Memory-safe, hard to access wrong memory

Cannot fully replace pointers Useful only for sending parameters

to functions

Page 53: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers vs. References References can point to only 1 variable Through their lifetime

References cannot be NULL References must be initialized on declaration

The address of a reference cannot be obtained The & operator returns the

variable's address

i.e. can't have pointer to reference or reference to reference

Page 54: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers vs. References Pointer arithmetics don't work on references

You can't make an array of references

It is a bad practice to return a reference It's usually ok to return a pointer

References usually implemented as const pointers in compilers Although the standard doesn't

dictate this

Page 55: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and ArraysArrays in Memory, Pointers and the []

Operator, Substituting Arrays with Pointers

Page 56: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and Arrays In memory, arrays are sequences of variables Which are sequences of bytes

i.e. an array is not fragmented in memory

A series of bytes, with a length of number of items * item type size

E.g.

on a system where sizeof(short) is 2, an array of 3 shorts, occupies a block of 6 bytes

0x13A2 0x13A3 0x13A4 0x13A5 0x13A6 0x13A7

short

short

short

Page 57: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and Arrays The address of an array

Is the same as the address of its first element

Arrays also keep other information like Array size, dimension size, etc.

Arrays often "degenerate" into pointers Most array operations can be done

with pointers

Arrays can't change the memory they point to Same as a const pointer

Page 58: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and Arrays The most important array "operator" – [] Is actually a syntax shorthand

Translates to pointer arithmetic

Addition is commutative, even for pointers:arrPtr + 3 == 3 + arrPtr == arr[3] == 3[arr](where int *arrPtr = arr)

int arr[5] {1, 2, 3, 4, 5};

int * arrPtr = arr; //We could also do the //operations below with arr//Тhe following lines print the samecout<<arr[3]<<" at "<<&arr[3]<<endl;cout<<3[arr]<<" at "<<&3[arr]<<endl;cout<<*(arrPtr + 3)<<" at "<<(arrPtr + 3)<<endl;

Page 59: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and Arrays The operator [] can be used with any pointer Does additive pointer arithmetic

Dereferences the result

i.e. adds number in brackets with the pointer Return value – the dereferenced

result pointer

A pointer can be used to Traverse, assign and read array-like

memory

Represent an array as a function parameter

Pointers essential in using dynamic memory

Page 60: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Pointers and ArraysLive Demo

Page 61: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory and Storage Types

"Stack" and "Heap" Memory, Storage Durations – automatic and dynamic

Page 62: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory and Storage Types

Programs usually use 2 types of memory Stack memory

Heap memory

Stack memory Separate for each process/thread

Stores function-local data, addresses, etc.

Automatically freed when out of scope

Heap memory Manual, dynamic alloc/dealloc,

usually larger

Page 63: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory and Storage Types

C++ utilizes stack and heap memory through Automatic storage – mapped to the

stack

Dynamic storage – works on the heap Some ways of dynamic storage on

the stack exist(mostly non-standard)

Storage types define how memory is managed When/where memory for variables

is allocated

What defines memory deallocation

Page 64: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory and Storage Types

C++ automatic storage – typical variables Variables local to functions

Function parameters

Basically all variable-related memory Pointers too – the address number,

not the data

C++ dynamic storage

Memory allocated with operator new (C++03) C++11 also offers Smart Pointers

Memory addresses are assigned to pointers

Page 65: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory and Storage Types

Notes on automatic storage Should be used for small data

Size known compile-time

Short lived – out of scope means deleted

Faster than dynamic

Freed upon function end. Don't return reference Ok to pass as a parameter by

reference/pointer

Bad to return by reference/pointer

Returned pointer/reference will point to deallocated (freed) memory

Page 66: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Memory and Storage Types

Notes on dynamic storage Useful when needed memory is not

known compile-time

Always accessed through pointers

Very agile for passing around the entire program's scope & lifespan

Manual allocation and deallocation E.g. the operators new and delete

Dynamic memory is shared, i.e. if you allocate all of it, other processes can't allocate

Page 67: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Working with Automatic and

Dynamic Storage in C++Initializing Automatic Variables,

Allocating and Deallocating Dynamic Memory

Page 68: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Automatic & Dynamic in C++

Automatic storage Variables you declare in functions

Including references and pointers as "numbers" i.e. addresses, not pointed memory

Arrays with size in declaration Compile-time known size arrays

auto keyword Explicitly denote automatic storage

until C++11

C++ 11 changes the meaning (old meaning wasn't really needed)

Page 69: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Automatic StorageLive Demo

Page 70: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Automatic & Dynamic in C++

Dynamic storage – memory allocated manually Through operators like new

Through functions like malloc

Through C++11 Smart Pointers

Deallocated manually If not deallocated can lead to a

"memory leak"

Memory is released by code, not automatically

Accessed through pointers

Page 71: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Automatic & Dynamic in C++

Using the new operator Initialization of a single instance of

a type new as prefix, type constructor

Initialization of multiple instances of a type i.e. array of objects of the type

new as prefix, typename, brackets with a number

Note: heapInt and heapArray are automatic, but the pointed memory is dynamic and will not be deallocated automatically

int *heapInt = new int();//value 0

int *heapArray = new int[5];//array of 5 random ints

Page 72: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Automatic & Dynamic in C++

Using the delete operator Frees up memory allocated with new

Freeing up a single instance of a type delete followed by pointer to the

memory

Freeing up multiple instances (arrays) of a type delete, brackets, pointer to memory

Note: if you lose all the pointers to the memory (they go out of scope), you can't deallocate it (unless you know its address)

delete heapInt;

delete[] heapArr;

Page 73: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Dynamic StorageLive Demo

Page 74: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

Summary References are just aliases of variables Can only represent one variable;

can be const

Pointers provide low level memory access Can point to any memory

address/variable

Can represent contiguous memory as arrays

Can move through memory (arithmetic)

We saw dynamic and automatic memory Dynamic memory implies new and delete

Local variables are automatic

Page 75: References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team  Telerik

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

References, Pointers and Memory

http://algoacademy.telerik.com