Sei sulla pagina 1di 3

C++ - Memory

VOID THE VERY EXCEPTIONAL TYPE


Despite the fact that the void type doesn't represent any useful value it is possible to declare
pointers to this type as in the following example
void *ptr;
You may ask how to use a pointer that points exactly at nothing and ask what such a pointer may
be useful for. That kind of pointer, which is precisely of the type void *, is named an amorphous
pointer to emphasize the fact that it is able to point to any value of any type. It means that the pointer
of type void * cannot be subject to the dereference operator, so you must not write anything similar
to this:
*ptr = 1;
It can be justified by the argument that if ptr was of type void * , *ptr would be of type void and the
assignment of a value of type int is prohibited by the compiler.
However, pointers of type void * are very useful when you need to have a pointer, but do not know
what purpose it may be used for in the future. As soon as it is clear, the pointer can easily be
converted into another pointer of the desired type (of course, a pointer one) which is always feasible
and does not cause any loss of accuracy.
MEMORY ON DEMAND
In the examples presented so far, memory management has taken place outside of our
consciousness. The parts of memory which we used to store values were hidden behind the names of
scalars and arrays. They appeared as soon as they had been declared and gone when our program
had ended operation. All work associated with memory allocation was organized by the compiler and
we didn't care how it works. This is how it should be - high level languages and their compilers are
designed to exonerate the developers' minds of such responsibilities.
It frequently happens that the developer wants to have full control over how much memory is used
and when exactly it is used. This is especially important when you do not know in advance, what the
size of the data to be processed is. To manage the allocating and freeing of the memory the C++
language provides two specialized keywords. Here, we present both of them for you
new
delete
The new keyword is used to request creation of a new memory block. When the allocated memory
is no longer needed and/or utilized, it would be a good habit to return it to the operating system. This
is done by the delete keyword.
The new keyword that performs the first-mentioned task can be used in the following way
float *array = new float [20];
int *count = new int;
it needs precise specification regarding the entity being created; it must be expressed as a
type description and if the created entity is an array, the size of the array must be given too
(like in the first example)
the new returns a pointer of type conforming the newly created entity
the newly allocated memory area is not filled (initiated) in any way so you should expect
that it contains just garbage
When the memory is no longer necessary we can release (free) it using the delete keyword in the
following way
delete [ ] array;
delete count;
we use delete [] form if we want to free the memory allocated for an array and delete
otherwise
you can only release the entire allocated block, not a part of it
after performing the free function all the pointers that point to the data inside the freed area
become illegal; attempting to use them may result in an abnormal program termination.

SS Puram, Tumkur | M.G. Road, Tumkur | Ph: +91-9620160796

C++ - Memory
We are going to present a complete, although not very useful, program that demonstrates the use of
both keywords.
We declare a variable called ptr which will point to the data of type int (the pointer's type is int
*); no value is assigned to this variable initially
We use the new keyword to allocate a block of memory sufficient to store a float array
consisting of 5 elements;
We make use of the newly allocated array (to be precise, a vector) and next we release it
using the delete keyword
We want you to pay attention to the fact that the pointer returned by new is treated as if it is an array.
Surprising?
The handling of the dynamic arrays (created during the run of the program) is no different than using
regular arrays declared in the usual way.
We owe it to the [] operator. Regardless of the nature of the array we can access its elements in the
same way.
#include <iostream>
using namespace std;
int main(void) {
float *arr;
arr = new float[5];
for(int i = 0; i < 5; i++)
arr[i] = i * i;
for(int i = 0; i < 5; i++)
cout << arr[i] << endl;
delete [] arr;
return 0;
}
The possibility of allocating the amount of memory which is really needed lets us write programs that
can adapt themselves to the size of the currently processed data. Let's go back to the bubble sort
algorithm that we presented previously. That program assumed that there were exactly 5 numbers to
sort. This is obviously a serious inconvenience. It may happen one day that we want to sort 10,000
numbers and sometimes hundreds of them. You can of course, declare an array of the maximum
predictable size but it would be unreasonable. A much better way is to ask the user how many
numbers will be sorted and then allocate the array of the appropriate size.
Let's try to start with a simpler example. In the following program we allocate an array containing 5
elements of type int, set their values, sum them up and, finally, release the previously allocated
memory.
int *tabptr, sum = 0;
tabptr = new int[5];
for(int i = 0; i < 5; i++)
tabptr[i] = i;
sum = 0;
for(int i = 0; i < 5; i++)
sum += tabptr[i];
delete [] tabptr;
The improved bubble sort program goes here We encourage you to compile and run the program
yourself.
#include <iostream>
using namespace std;

SS Puram, Tumkur | M.G. Road, Tumkur | Ph: +91-9620160796

C++ - Memory
int main(void) {
int *numbers, how_many_numbers;
int aux;
bool swapped;
cout << "How many numbers are you going to sort? ";
cin >> how_many_numbers;
if( how_many_numbers <= 0 || how_many_numbers > 1000000) {
cout << "Are you kidding?" << endl;
return 1;
}
numbers = new int[how_many_numbers];
for(int i = 0; i < how_many_numbers; i++) {
cout << "\nEnter the number #" << i + 1 << ": ";
cin >> numbers[i];
}
do {
swapped = false;
for(int i = 0; i < how_many_numbers - 1; i++)
if(numbers[i] > numbers[i + 1]) {
swapped = true;
aux = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = aux;
}
} while(swapped);
cout << endl << "The sorted array:" << endl;
for(int i = 0; i < how_many_numbers; i++)
cout << numbers[i] << " ";
cout << endl;
delete [] numbers;
return 0;
}

SS Puram, Tumkur | M.G. Road, Tumkur | Ph: +91-9620160796

Potrebbero piacerti anche