You are on page 1of 5

LAB 12

DYNAMIC MEMORY

12.1 OBJECTIVES

- To understand the difference between heap and stack


- To know about new and delete operator
- To know the significance of dynamic memory allocation
- To have an idea about dangling pointer

12.2 PRE-LAB READING

12.2.1 MEMORY MANAGEMENT

We have seen many examples where arrays are used to set aside memory. The following statement
reserves memory for 100 integers.

int arr1[100];

Arrays are a useful approach to data storage, but they have a serious drawback: We must know at the
time we write the program, how big the array will be. We can’t wait until the program is running to
specify the array size. The following approach won’t work:

cin >> size; // get size from user


int arr[size]; // error; array size must be a constant

That means the compiler requires the array size to be a constant. But in many situations we don’t know
how much memory we need until runtime.

Memory in your C++ program is basically divided into two parts:


 The stack: All variables declared inside the function will take up memory from the stack.
 The heap: This is unused memory of the program and can be used to allocate the memory
dynamically when program runs.

As far as we have learnt about variable and arrays, these were occupying a space on stack. But to cope
with a situation described above, operating system gives us the privilege to use an unemployed
memory, the heap. So the size of an array could be acquired from the user by allocating dynamic
memory on heap.

1
12.2.2 NEW & DELETE OPERATORS

When the memory needed depends on user input, programs need to dynamically allocate memory, for
which the C++ language integrates the operators new and delete.

new Operator:
Dynamic memory is allocated using operator new. new is followed by a data type specifier. It returns a
pointer to the beginning of the new block of memory allocated. This pointer can be captured in any
pointer variable. Its syntax is:

ptr = new data_type

Where ptr is a pointer variable and suppose it was declared before this statement.

delete Operator:
In most cases, memory allocated dynamically is only needed during specific periods of time within a
program; once it is no longer needed, it can be freed so that the memory becomes available again for
other requests of dynamic memory. This is the purpose of operator delete, whose syntax is:

delete ptr;

To ensure safe and efficient use of memory, the new operator is matched by a corresponding delete
operator that returns memory to the operating system. This will also save your system to be crashed or
malfunctioned.

12.2.3 DYNAMIC ARRAYS

A dynamic array is an array whose size is not specified when you write the program, but is determined
while the program is running.
To declare such arrays we again use new operator as:

ptr = new data_type [number_of_elements]

The magic of array/pointer duality lets you use the array notation ptr[i] to access the ith element.
When your program no longer needs memory that you previously allocated with the new operator, you
must return it to the heap, using the delete operator:

delete[] ptr;

delete operator with brackets reminds the heap that the pointer points to an array, not a single value.

Activity 1

Given the definitions

double primes[] = { 2, 3, 5, 7, 11, 13 };


double* p = primes + 3;

2
draw a diagram that explains the meanings of the following expressions:

a. primes[1]

b. primes + 1

c. *(primes + 1)

d. p[1]

e. p + 1

12.2.4 DANGLING POINTER

A very common pointer error is to use a pointer that points to memory that has already been deleted.
Such a pointer is called a dangling pointer. Because the freed memory will be reused for other purposes,
you can create real damage by using a dangling pointer. Consider this example:

int* values = new int[n];


// Process values
delete[] values;
// Some other work
values[0] = 42;

This code will compile since the compiler does not track whether a pointer points to a valid memory
location. However, the program may run with unpredictable results. If the program calls the new
operator anywhere after deleting values, that call may allocate the same memory again. Now some
other part of your program accesses the memory to which values points, and that program part will
malfunction when you overwrite the memory. This can happen even if you don’t see any call to new—
such calls may occur in library functions.

Activity 2:
Find the error and make it correct as well.
a) int *number;
cout << number << endl;

b) double *realPtr;
long *integerPtr;
integerPtr = realPtr;

c) int * x, y;
x = y;

3
12.3 LAB TASKS

1. Write a program which asks to enter the data of some students in an array. User will have to
provide the name of student and marks obtained (out of 100) in the course of “Computer
Programming”. Afterwards, simply show the results based on following standard:
Grade A: marks > 90
Grade B: marks > 70
Grade C: marks > 60
Fail: otherwise
(marks 25)

2. Write a function
double replace_if_greater(double* p, double x)

that replaces the value to which p points with x if x is greater. Return the old value to which p
pointed.
(marks 25)

3. Write a program which allows the students to appear in upcoming semester as a regular student
or not, based on their CGPA. It must asks the number of enrolled students in a batch, their
registration id and then their CGPA. All the students having points less than 2.0 are not allowed
to appear in next semester. Your program should blacklist those registration ids and display on
the screen.
(marks 25)

4. Make your own version of the library function strcmp(s1, s2), which compares two strings and
returns –1 if s1 comes first alphabetically, 0 if s1 and s2 are the same, and 1 if s2 comes first
alphabetically. Call your function compstr(). It should take two char* strings as arguments,
compare them character by character, and return an int. Write a main() program to test the
function with different combinations of strings. Use pointer notation throughout.
(marks 25)

4
12.4 POST-LAB ACTIVITY
1. You run four computer labs. Each lab contains computer stations that are numbered as shown in
the table below:

Lab Number Computer Station Number

1 1-5

2 1-6

3 1-4

4 1-3

Each user has a unique five-digit ID number. Whenever a user logs on, the user’s ID, lab number,
and the computer station number are transmitted to your system. For example, if user 49193
logs onto station 2 in lab 3, then your system receives (49193, 2, 3) as input data. Similarly,
when a user logs off a station, then your system receives the lab number and computer station
number. Write a computer program that could be used to track, by lab, which user is logged
onto which computer. For example, if user 49193 is logged into station 2 in lab 3 and user 99577
is logged into station 1 of lab 4 then your system might display the following:

Lab Number Computer Stations


1 1: empty 2: empty 3: empty 4: empty 5: empty
2 1: empty 2: empty 3: empty 4: empty 5: empty 6: empty
3 1: empty 2: 49193 3: empty 4: empty
4 1: 99577 2: empty 3: empty

Create a menu that allows the administrator to simulate the transmission of information by
manually typing in the login or logoff data. Whenever someone logs in or out, the display should
be updated. Also write a search option so that the administrator can type in a user ID and the
system will output what lab and station number that user is logged into, or “None” if the user ID
is not logged into any computer station. You should use a fixed array of length 4 for the labs.
Each array entry points to a dynamic array that stores the user login information for each
respective computer station.