1. Arrays declared with a fixed size limit the program size, while dynamically allocated arrays using heap memory allow the size to be determined at runtime.
2. The heap segment is used for dynamic memory allocation using functions like malloc() and new to request memory from the operating system as needed.
3. Deallocation of dynamically allocated memory is required using free() and delete to avoid memory leaks and ensure memory is returned to the operating system.
1 of 16
More Related Content
Dynamic memory allocation in c++
2. PROBLEMS WITH NORMAL ARRAY
VARIABLE DECLARATION
Int main() // 1 . Size fixed
{
1020 1022 1024 1026 1028
Int A[5]; A[0] A[1] A[2] A[3] A[4]
Int B[n]; // 2. Error..Size must be known at
compile time.
}
Will not work for larger programs because of the limited size of the
stack.
3. HEAP AND STACK
Our program when loaded in to main memory is divided in to 4
segments : CODE,DATA,STACK,HEAP
A data segment contains the global variables and static variables.
A code(text) segment contains the executable instructions.
A Stack segment store all the auto variables. Also each function call
involves passing arguments from the caller to the callee. The callee
may also declare variables. Function parameters ,return address
and automatic local variables are accommodated in the stack.
Hence a stack is an area of memory for storing data temporarily.
4. Allocation and de allocation of memory in this area is done
automatically .
Heap segment is for dynamic memory management.
It is for the programmers to manage.
We can allocate memory when you feel the need for it and delete
when you feel that the memory is no longer needed
And it is the responsibility of the programmer to delete memory
when no longer needed.
Hence for array we can dynamically allocate memory of size which
can be determined at run time.
C programs use a pair of functions named malloc and free to
allocate space from the heap.
In C++ we use new and delete.
5. DEFINING A DYNAMIC ARRAY
When we define an array variable, we specify a type , a name, and a
dimension.
int a[2]
When we dynamically allocate an array, we specify the type and size
but no name
This new expression allocates an array of ten integers and returns a
pointer to the first element in that array, which we use to initialize ptr.
int *ptr = new int[10];
// array of 10 uninitialized integers (contain garbage value)
Objects allocated on the free store are unnamed. We use objects on
the heap only indirectly through their address.
6. To value initialise the array we can use empty parentheses in the
expression.
int *pia2 = new int[10] (); // initialized to 0
This effectively send a request to the compiler to value-initialize the
array, which in this case sets its elements to 0.
The elements of a dynamically allocated array can be initialized only to
the default value of the element type.
The elements cannot be initialized to separate values as can be done
for elements of an array variable.
int a[2]={1,2};
7. int* nums2 = new int[x]; // ok
Value of x is obtained during run time and even the memory
allocation is done dynamically
For multidimensional arrays
int x = 3, y = 4;
int* nums3 = new int[x][4][5]; // ok
int* nums4 = new int[x][y][5]; // BAD!
Only the first dimension can be a variable. The rest must be
constants.
8. DEALLOCATING MEMORY
When we allocate memory, we must eventually free it.
Otherwise, memory is gradually used up and may be exhausted
We do so by applying the delete [] expression to a pointer that
addresses the array we want to release:
delete [ ] ptr; //de allocates the array pointed to by ptr
The empty bracket pair between the delete keyword and the pointer is
necessary
It indicates to the compiler that the pointer addresses an array of
elements
It is essential to remember the bracket-pair when deleting pointers to
arrays.
For every call to new, there must be exactly one call to delete.
9. MALLOC AND FREE
Memory allocation can be done using malloc as:
int* nums = (int*)malloc(5*sizeof(int));
This is similar to int *nums = new int[5];
De allocation can be done using free as
free(nums)
This is similar to delete[ ] nums.
C++ also supports malloc and free as we know that C++ is a
superset of C.
10. WHY NEW IF MALLOC ?
With simple variables and arrays new and delete does the same
functionality as malloc and free respectively.
But the scenario changes when we need to work with the classes
where we use constructors to assign values to the data members.
As with classes new allocates space to hold the object which are the
instance of the class.
new calls the object’s default constructor.
Example : for a given class ‘cls’ ,
cls *ptr = new cls; // calls default constructor of cls. If not found
, automatically compiler generated
constructor is called
11. cls *ptr = new cls(2); // calls one parameterized constructor of cls.
If not found , throws error
new returns a pointer to the object of the class.
Though malloc does allocate memory for the given type it cannot call
the constructor which are the special member functions that are used
to assign values to variables.
new is an operator, while malloc() is a function.
new returns exact data type, while malloc() returns void pointer
15. OUTPUT:
a=56378
// Garbage value
// Didn’t call neither the constructor nor the destructor
16. CAUTION: MANAGING DYNAMIC
MEMORY IS ERROR-PRONE
Some common program errors are associated with dynamic
memory allocation:
Failing to delete a pointer to dynamically allocated
memory, thus preventing the memory from being returned to
the free store. Failure to delete dynamically allocated memory
is spoken of as a "memory leak.”
Applying a delete expression to the same memory location
twice. This error can happen when two pointers address the
same dynamically allocated object. If delete is applied to one
of the pointers, then the object's memory is returned to the
free store. If we subsequently delete the second pointer, then
the free store may be corrupted.