Download presentation
Presentation is loading. Please wait.
1
Pointers and Memory Overview
In this lesson we will address several very important issue We will explore in some depth Variable addresses How to work with such addresses We’ll also cover the associated topics of Static and dynamic storage allocation and management Storage classes Copyright 2001 Oxford Consulting, Ltd 1 January 2001
2
Pointers and Memory Pointers Variables Storing Data
Variables one is most familiar with hold data We have such declarations as int myAge = 39; float mySpeed = 54.52; char myAnswer = ‘t’; Know data stored in memory somewhere but there are questions How does one know where data is stored? Are large data objects stored the same way as smaller? How do I pass a large data object to a function? Can I put a 200 m byte object on the stack? Do I want to? Copyright 2001 Oxford Consulting, Ltd 1 January 2001
3
Pointers and Memory Pointers see how to begin to answer these questions As we’ve seen, each variable is holding data That data is stored in memory In some location Each memory location has an address For each piece of data We have a value We have the place that it is stored - its address Copyright 2001 Oxford Consulting, Ltd 1 January 2001
4
Pointers and Memory Pointers Variables Storing Addresses
In C++ the value of a variable can be a memory address We give such a variable a special name Called a pointer Thus….. A pointer is a variable Exactly like the variables we’ve been studying Pointers hold values that are addresses in memory Copyright 2001 Oxford Consulting, Ltd 1 January 2001
5
Pointers and Memory Pointers
Consider a standard C++ declaration and assignment int j = 3; Such declaration achieves the following Allocates 32 bits of memory on a 32 bit machine Places value 3 ( 0003H) into those 32 bits Associates an address in memory where data stored with the symbol j When we write j we are actually referring to data at that location If wish to know where data is stored we use the address of operator & Copyright 2001 Oxford Consulting, Ltd 1 January 2001
6
Pointers and Memory Pointers Thus &j (read address of j) is 3000
If aPtr is variable that holds the address of variable aPtr = &j; // sets aPtr to point to the variable j Copyright 2001 Oxford Consulting, Ltd 1 January 2001
7
Pointers and Memory Pointers
We can retrieve value that aPtr points at ….. We use dereference operator * We write…. *aPtr …..To indicate the value at address contained in aPtr Thus the code fragment…. Retrieves value in memory that aPtr is referring to Assigns value 3 to variable b int b; // assume b stored in location 3060 b = * aPtr; // assigns the value 3 to variable b Copyright 2001 Oxford Consulting, Ltd 1 January 2001
8
Pointers and Memory Pointers In memory we have...
Copyright 2001 Oxford Consulting, Ltd 1 January 2001
9
Pointers and Memory Pointers Similarly the code fragment
Places the value 4 into the memory location 3000 int c = 4; // assume c stored in location 3040 *aPtr = c; Copyright 2001 Oxford Consulting, Ltd 1 January 2001
10
Pointers and Memory Pointers /* * A First Look at Pointers
* Playing with pointers. */ #include <iostream> using namespace std; int main(void) { int x=1, y=2, z; int *aPtr; // aPtr is a pointer to int aPtr = &x; // aPtr now points to x z = *aPtr; // z is now 1 cout << "The value of z is: " << *aPtr << endl; *aPtr = y; // x is now 2 cout << "The value of x is: " << *aPtr << endl; (*aPtr)++; // x is now 3 *aPtr++; // x is now ??? return 0; } Copyright 2001 Oxford Consulting, Ltd 1 January 2001
11
Pointers and Memory Pointers Observe we had to write (*aPtr)++
What do we get with ????? * aPtr ++ Let aPtr point to address 3000 Since ++ is left associative and higher precedence than * It’s the same as writing *( aPtr ++) Thus…. 1. aPtr <- 3020 2. The contents of location 3020 retrieved and discarded By writing (*aPtr)++ We get what aPtr is pointing at Then increment that value Copyright 2001 Oxford Consulting, Ltd 1 January 2001
12
Pointers and Memory Pointers
Why does aPtr ++ yield 3020 rather than 3001??????? In C++ A pointer advances in increments of the size of the element pointed to aPtr declared as pointer to int Therefore incremented in sizeof (int) If aPtr had been declared as double Then for (aPtr) = 3000 aPtr ++ Gives also give 3040 Copyright 2001 Oxford Consulting, Ltd 1 January 2001
13
Pointers and Memory Pointers Pointers and Numbers…..
Pointers are not integer types… …this means we cannot assign a pointer a number value int a; // declare an int int* aPtr; // declare a pointer to an int float* fPtr; // declare a pointer to a float aPtr = 10; // compile error // aPtr is a pointer and cannot contain an integer a = &aPtr; // compile error // a is an integer and cannot contain an address aPtr = 1.25f; // compile error // aPtr pointer and cannot contain a float aPtr = &fp; // compile error // aPtr is a pointer to int and cannot contain the address // of a float Copyright 2001 Oxford Consulting, Ltd 1 January 2001
14
Pointers and Memory Pointers
The compiler is assuring that contents of pointer is the address of a variable of the pointer's type It’s making sure that types are used in a safe and consistent manner This is called type safety For this reason, C++ is termed a more strongly typed language Copyright 2001 Oxford Consulting, Ltd 1 January 2001
15
Pointers and Memory Pointers Pointers and cout
When we display a pointer using cout …. … What is displayed is the address contained in the pointer It’s the same as when we display an int We see the value contained in the int Copyright 2001 Oxford Consulting, Ltd 1 January 2001
16
Pointers and Memory Pointers int data = 10; // declare an int
int* dataPtr = &data; // declare a pointer to it cout << data; // displays 10 cout << dataPtr; // displays the contents of variable dataPtr // which is the address of the variable data cout << *dataPtr; // displays the contents of the variable data Copyright 2001 Oxford Consulting, Ltd 1 January 2001
17
Pointers and Memory Pointers Simple Pointer Arithmetic Question????
If we let aPtr = 3000 and We’ve seen aPtr++ = 3020 Then what does aPtr + 1 = ? The compiler knows the type of variable pointed to Thus…. aPtr + 1 is no different from aPtr ++ ….and consequently aPtr ++ aPtr + 1 Copyright 2001 Oxford Consulting, Ltd 1 January 2001
18
Pointers and Memory Pointers Simple Pointer Arithmetic A caution...
With aPtr = 3000, we know * aPtr = 0003 *( aPtr ++) refers to 3020 *( aPtr + 1) refers to 3020 What does * aPtr + 1 yield???? 1. The pointer will be evaluated This returns 0003 2. Then 1 is added to 0003 The result is 0004 If this was intended…then, ok otherwise we need to use parentheses Copyright 2001 Oxford Consulting, Ltd 1 January 2001
19
Pointers and Memory Pointers Simple Pointer Arithmetic Cannot Add
Multiply Divide Multiply or Divide By scalar Can Subtract 2 pointers Result is an int Copyright 2001 Oxford Consulting, Ltd 1 January 2001
20
Pointers and Memory Pointers Simple Pointer Arithmetic
If we want to do binary search on array, we need to find mid point of array We know …. First address of array Last address of array Copyright 2001 Oxford Consulting, Ltd 1 January 2001
21
Pointers and Memory Pointers Simple Pointer Arithmetic
Address of midpoint is easily computed Number of bytes above and below mid point given as Thus midpoint is given as Which is the address we had hoped find by Copyright 2001 Oxford Consulting, Ltd 1 January 2001
22
Pointers and Memory Dynamic Memory
Let’s now look at a topic that is related to pointers and pointer manipulation We’ll work with what we call dynamic memory Dynamic memory is memory that is allocated while our program is executing So far all of our examples have relied upon static allocation Such memory is allocated during compilation We can't change it at run time Copyright 2001 Oxford Consulting, Ltd 1 January 2001
23
Pointers and Memory Dynamic Memory
The variables we’ve been working with called Automatic or auto variables Memory for such variables is Temporary and Managed by the system for us Copyright 2001 Oxford Consulting, Ltd 1 January 2001
24
Pointers and Memory Dynamic Memory
Dynamically allocated memory is persistent, we will own that memory until we explicitly relinquish ownership If we forget to do so that amount of memory is no longer available to our program Should we continue to allocate more memory and not release it the available memory is further reduced Such reduction in available memory is called a memory leak Copyright 2001 Oxford Consulting, Ltd 1 January 2001
25
Pointers and Memory Dynamic Memory
In our programs memory leaks occur for two main reasons... We allocate memory and forget to return We loose the address needed to return the memory Memory leaks are very serious errors To avoid leaks consider where and how memory will be returned …..At the time you allocate it Copyright 2001 Oxford Consulting, Ltd 1 January 2001
26
Pointers and Memory Dynamic Memory new and delete operators
The C language has functions malloc free To manage allocation and deallocation of memory at runtime The C++ language introduces the operators new delete To accomplish related tasks Copyright 2001 Oxford Consulting, Ltd 1 January 2001
27
Pointers and Memory Dynamic Memory new and delete operators
new operator Gives programmer control over storage allocation Allocated from heap at runtime Similar to malloc delete operator Gives programmer control over storage deallocation Deallocated at runtime and returned to the heap Similar to free Copyright 2001 Oxford Consulting, Ltd 1 January 2001
28
Pointers and Memory Dynamic Memory new operator
The new operator is written in several ways Two forms for allocating single variable One version permits specification of initializing value Other version merely allocates One form for allocating array of variables Syntax new type // Allocate new type ( value ) // Initialize to value // Cannot apply to an array or array type Syntax new type [amount] returns on success pointer to newly allocated memory by default memory is not initialized on failure NULL Copyright 2001 Oxford Consulting, Ltd 1 January 2001
29
Pointers and Memory Dynamic Memory new operator int *myPtr = new int;
Allocate sufficient storage to hold a single integer Pointer to storage assigned to myPtr char *myPtr = new cha(‘a’); Allocate sufficient storage to hold a single character Initialize the storage to the value ‘a’ Pointer to storage assigned to myPtr char * myPtr = new char [ strlen (“Bon jour mes amis”) + strlen (“touts les jour”) + 1]; Returns a pointer to an area of memory Large enough to hold characters Remember strlen does not count null character Copyright 2001 Oxford Consulting, Ltd 1 January 2001
30
Pointers and Memory Dynamic Memory delete operator
The delete operator returns the memory Allocated by new to free memory. Note: Dynamically allocated memory Often called the free store or the heap Copyright 2001 Oxford Consulting, Ltd 1 January 2001
31
Pointers and Memory Dynamic Memory delete operator
The following are undefined….. Applying the delete operator to an object not created by new Result of accessing a deleted object is undefined Copyright 2001 Oxford Consulting, Ltd 1 January 2001
32
Pointers and Memory Dynamic Memory delete operator
Like new operator ….. …the delete operator is written in several ways One form for de-allocating single variable One form for de-allocating array of variables Syntax delete expression Syntax delete [ ] expression Copyright 2001 Oxford Consulting, Ltd 1 January 2001
33
Pointers and Memory Dynamic Memory delete operator
Which ever form is used The expression that is deleted Must be a pointer to memory allocated by new Must use delete [] to free string to heap Deleting an array with delete Undefined Deleting a single object with delete[] Copyright 2001 Oxford Consulting, Ltd 1 January 2001
34
Pointers and Memory Dynamic Memory delete operator
Cannot delete a pointer to a const This would change the value of a const const int *aPtr = new int (1024); delete aPtr; // compile error Copyright 2001 Oxford Consulting, Ltd 1 January 2001
35
Pointers and Memory Pointers Pointers and C-Strings
Up to now a C-string has been declared as char str[5 + 1]; strcpy(str, "Hello"); The variable str is an array of chars The name str represents the address of the array If str is the address of the array Then it must be a variable that contains an address Here str is a pointer to char ( a char*) and Can be used in any function argument as a char* Copyright 2001 Oxford Consulting, Ltd 1 January 2001
36
Pointers and Memory Pointers Pointers and C-Strings
Using this information The str array can be dynamically allocated by char* str = new char[6]; strcpy(str,"Hello"); Remember when we delete it we must use delete[ ] Copyright 2001 Oxford Consulting, Ltd 1 January 2001
37
Pointers and Memory Pointers Simple Pointer Arithmetic
Let’s dynamically allocate some memory to hold an array of ints int* intPtr = new int[5]; Here intPtr contains the address of array element[0] The value of that element can be changed by * intPtr = 10; The operation assigns 10 to the array element pointed at by intPtr Copyright 2001 Oxford Consulting, Ltd 1 January 2001
38
Pointers and Memory Pointers Simple Pointer Arithmetic
Now let’s do this….. intPtr ++; Adding one to intPtr increments the address contained inside intPtr by the size of one integer So, in this case * intPtr = 25; Will change array element[1] to 25 Here is our first memory leak. Do you see it? Copyright 2001 Oxford Consulting, Ltd 1 January 2001
39
Pointers and Memory Pointers Simple Pointer Arithmetic
The problem is that the address that intPtr points to has been changed It was used earlier to hold the address ff the array returned by the new operator …..Now that address is lost and it will be difficult to release this array without extra work Copyright 2001 Oxford Consulting, Ltd 1 January 2001
40
Pointers and Memory Pointers Simple Pointer Arithmetic
We can avoid this by never changing a pointer that was returned by the new operator Instead assign the address to a temporary pointer then do pointer arithmetic using the temporary pointer …..Even so we must still be careful not to exceed the bounds of the array int* const intPtr = new int[5]; // intPtr has array address int* temp = intPtr; // create temp pointer and assign array address temp++; // OK to change temp …. delete [] intPtr; // intPtr is unchanged Copyright 2001 Oxford Consulting, Ltd 1 January 2001
41
Pointers and Memory Memory Storage Classes
Exactly how a variable, array, or struct instance is stored is based on the storage class of the object We’ve been using storage classes but haven't noticed them We’ve been using only the default storage classes Copyright 2001 Oxford Consulting, Ltd 1 January 2001
42
Pointers and Memory Memory Storage Classes We can store our objects
Locally within a function, a block, or even as a parameter to a function Which is the automatic storage class Such that they exist for the life of the program Which is the static storage class When we are using the automatic storage class, the compiler will automatically create and delete the storage Copyright 2001 Oxford Consulting, Ltd 1 January 2001
43
Pointers and Memory Memory Storage Classes
Both variables in following function use the automatic storage class void aFunction() { int a; // auto is assumed auto int b; } Copyright 2001 Oxford Consulting, Ltd 1 January 2001
44
Pointers and Memory Memory Storage Classes
Auto memory is often called the stack One such structure is used Manage the local variables and Return values of functions C++ programmers often say that a variable is allocated on the stack When they mean to say that it is allocated locally inside the function Copyright 2001 Oxford Consulting, Ltd 1 January 2001
45
Pointers and Memory Summary and Review
You should now be beginning to get comfortable with Pointers Pointer arithmetic You should be able to dynamically create variables and arrays using the C++ new and delete operators You are able to use storage classes To instruct the compiler where to store your variables. Copyright 2001 Oxford Consulting, Ltd 1 January 2001
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.