CS3240: Data Structures and Algorithms

Data Structures: Pointers and Memory Issues

Pointers

A pointer variable is a variable whose value is the address of a location in memory. To declare a pointer variable, you must specify the type of value that the pointer will point to. For example,


int*   ptr;   //ptr will hold the address of an int

char*  q;     //q will hold the address of a char

Getting Pointer to a Variable

The address of a non-array variable can be obtained by using the address-of operator &.


using namespace std;
int     x;
float   number;
char    ch;

cout << “Address of x is “ << &x << endl;

cout << “Address of number is “ << &number << endl;

cout << “Address of ch is “ << &ch << endl;

Array name is a Pointer

char msg [ 8 ];

msg is the base address of the array.

  • We say msg is a pointer because its value is an address.
  • It is a pointer constant because the value of msg itself cannot be changed by assignment. It “points” to the memory location of a char.

Using Pointers....An Example


int  x;
 x = 12;


 int*  ptr;
 ptr = &x;

 *ptr = 5;   // changes the value at adddress ptr to 5
           

Some Pointer Operations

Dangling Pointer

occurs when two pointers point to the same object and delete is applied to one of them

 

 

 

Dynamic Allocation using Pointers - new and delete

Example Allocation and Deallocation using new and delete

using namespace std;

Node *ptr = new Node; // where Node is a class.

...

delete ptr; // Later on we get rid of the allocated memory pointed to by ptr

 

PROBLEM -- you CAN NOT delete statically created items

Node abc; //this is "statically created in memory called the node constructor
Node *abc_ptr = &abc;

free(abc_ptr); //PROBLEM !! can not do

 

Special Note about new/delete and malloc/free

  • new/delete is preferred to malloc()/free() because it can initialize the memory
    and it invokes the constructor for new objects.
  • new/delete also point to the correct memory type.
  • Note on mixing source code containing new/delete and malloc()/free(). This is not a problem with the GNU C++ compiler but this is not guaranteed for all C++ compilers. BUT--why do it, don't

 

© Lynne Grewe