Wednesday, May 5, 2010

Dynamic memory allocation

The way dynamic memory allocation and deallocation is done in C++ differs from C in a way that on the surface may seem rather unimportant, but in fact the difference is enormous and very valuable.
Here's a small demo of dynamic memory allocation and deallocation (ignoring error handling).
int main(void)
{
int* pint = new int; // 1
*pint = 1;
int* pint2 = new int(2); // 2
Range* pr = new Range(1,10); // 3
// Range from the previous example.
delete pint; // 4
delete pint2; // 4
delete pr; // 4
return 0;
}
Dynamic memory is allocated with the "new" operator. It's a built in operator that guarantees that a large enough block of memory is allocated and initialised, (compare with "malloc" where it's your job to tell how large the block should be and what you get is raw memory) and returns a pointer of the requested type. At //1 you see an "int" being allocated on the heap, and the pointer variable "pint" being initialised with its value. At //2 and //3 you see another interesting thing about the "new" operator; it understands constructors. At //2 an "int" is allocated on heap, and the "int" is initialised with the value 2. At //3 a "Range" struct is allocated on the heap, and initialised by a call to the constructor defined in the previous example. As you can see at //4 dynamic memory is deallocated with the built in "delete" operator.

No comments:

Post a Comment