Dynamic Memory - shahzade baujiti

Breaking

Wednesday, April 24, 2019

Dynamic Memory

10.2
Dynamic Memory

Allocating memory

There are two ways that memory gets allocated for data storage:
Compile Time (or static) Allocation
- Memory for named variables is allocated by the compiler
- Exact size and type of storage must be known at compile time
- For standard array declarations, this is why the size has to be constant

Dynamic Memory Allocation
- Memory allocated "on the fly" during run time
- dynamically allocated space usually placed in a program segment known as the heap or the free store.
- Exact amount of space or number of items does not have to be known by the compiler in advance.
- For dynamic memory allocation, pointers are crucial.

Dynamic Memory Allocation

We can dynamically allocate storage space while the program is running, but we cannot create new variable names "on the fly"

For this reason, dynamic allocation requires two steps:
- Creating the dynamic space.
- Storing its address in a pointer (so that the space can be accesed)

To dynamically allocate memory in C++, we use the new operator.

De-allocation:
- Deallocation is the "clean-up" of space being used for variables or other data storage
- Compile time variables are automatically deallocated based on their known extent (this is the same as scope for "automatic" variables)
- It is the programmer's job to deallocate dynamically created space
- To de-allocate dynamic memory, we use the delete operator

Allocating space with new

To allocate space dynamically, use the unary operator new, followed by the type being allocated.

new int;
// dynamically allocates an int
new double;
// dynamically allocates a double

If creating an array dynamically, use the same form, but put brackets with a size after the type:
new int[40];
// dynamically allocates an array of 40 ints
new double[size];
// dynamically allocates an array of size doubles

These statements above are not very useful by themselves, because the allocated spaces have no names! BUT, the new operator returns the starting address of the allocated space, and this address can be stored in a pointer:
int * p;
// declare a pointer p
p = new int;
// dynamically allocate an int and load address into p

Deallocation of dynamic memory

To deallocate memory that was created with new, we use the unary operator delete. The one operand should be a pointer that stores the address of the space to be deallocated:
int * ptr = new int;
// dynamically created int
...
delete ptr;
// deletes the space that ptr points to

Note that the pointer ptr still exists in this example. That's a named variable subject to scope and extent determined at compile time. It can be reused:
ptr = new int[10];
// point p to a brand new array

To deallocate a dynamic array, use this form:
delete [] name_of_pointer;



No comments:

Post a Comment