You are on page 1of 16

PROBLEMS WITH NORMAL ARRAY VARIABLE DECLARATION

Int main() { Int A[5];


Int B[n];

// 1 . Size fixed
1020 A[0] 1022 A[1] 1024 A[2] 1026 A[3] 1028 A[4]

// 2. Error..Size must be known at compile time.

} Will not work for larger programs because of the limited size of the stack.

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.

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.

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.

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};

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]; int* nums4 = new int[x][y][5];

// ok // BAD!

Only the first dimension can be a variable. The rest must be constants.

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.

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.

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 objects 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

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

EXAMPLE:
#include<iostream> Using namespace std; class cls { int a; public: cls() { a=5; cout<<"\nConstructor called"; } ~cls() { cout<<"\nDestructor called"; } void disp() { cout<<"\na:"<<a; } }; void main() { clrscr(); cls *ptr = new cls; ptr->disp(); delete ptr; getch(); }

OUTPUT:
Constructor called a=5 Destructor called

EXAMPLE:
#include<iostream> Using namespace std; class cls { int a; public: cls() { a=5; cout<<"\nConstructor called"; } ~cls() { cout<<"\nDestructor called"; } void disp() { cout<<"\na:"<<a; } }; void main() { clrscr(); cls *ptr = (cls*)malloc(sizeof(cls)) ptr->disp(); free(ptr); getch(); }

OUTPUT:
a=56378

// Garbage value // Didnt call neither the constructor nor the destructor

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.

You might also like