Thursday, February 25, 2010

Dynamic memory allocation in C and C++

Sometimes, when we want to declare a certain array, but we don't know the length of it or we want it to be specified during the running process, we can use the technique of allocating memory spaces dynamically.

In C we use it like this. (We need to include stdlib.h in front of the program)
Datatype* variable = (Datatype*) malloc ( maxindex * sizeof(Datatype));

Eg.
int* d = (int*) malloc (8 * sizeof(int));
Then we can treat d as a normal array. We can assign value to each element
int i = 0;
for(i = 0; i < 8; i++) d[i] = i * 10;

It is important to free the memory space to avoid memory leak;
To free memory we say:
free(d);


In C++ we have "new" and "delete", and the way to use is like this:
double* p = new double [5]; // created 5 objects for double
// delete [] p; to delete
Employee* e = new Employee; // created one objects for class Employee, the default constructor is called.
// delete e; to delete
using member function: e->display();

The other thing we need to consider is how to copy the content of an array to another, both of which are dynamically allocated.
1. Create a same datatype pointer (we call it destination here).
2. Allocate a proper amount of space for the destination.
3. Copy the content from the source to the destination.
4. Delete the content of the source. Get rid of the old one.
5. Make the older pointer (we call it source here) pointing to the destination.
6. Because the destination is local, so after function calling, it will be gone automatically.

During next week, I am going to create a class containning a void pointer as a data member that can be used like the dynamic array.

1 comment:

  1. Just use Deleaker ( http://deleaker.com/ ) to avoid memory leaks!

    ReplyDelete