Tuesday, May 5, 2020

Dynamic Memory Allocation free essay sample

Every Data or Instruction to be processed must be loaded into internal memory before its processing takes place. This process is called Memory allocation. These are of two types: Static and Dynamic Memory Allocation. First let’s talk about Static memory allocation. Here we reserve a certain amount of memory by default inside our program to use for variables, etc and this static memory is allocated during the compilation of the Program. Once we reserve this memory, no other program can use it, even if we are not using it at the time. But many times we are not aware in advance about how much memory we will need to store particular information in a defined variable. The size of required memory may be determined only during the run time , i. e. when the program is being run. Here Dynamic memory comes into play. By using Dynamic memory allocation, the programmer can allocate memory to a program during run time. We will write a custom essay sample on Dynamic Memory Allocation or any similar topic specifically for you Do Not WasteYour Time HIRE WRITER Only 13.90 / page The program uses its allocated memory only when it is active. In its inactive state, the program will use much less memory, hence allowing other programs to take up the unused memory. You can even de allocate memory so as to free up memory for other programs, but we need to do this manually. In C++, an operator called new is used for Dynamic memory allocation. To allocate a single variable dynamically, we use the following syntax: int *data = new int; // dynamically allocate an integer named data. The new operator returns the address of the variable that has been allocated. This address can be stored in a pointer, and the pointer can then be dereferenced to access the variable. int *data = new int; // dynamically allocate an integer *data = 7; // assign 7 to this integer When we are done with a dynamically allocated variable, we need to explicitly tell C++ to free the memory for reuse. This is operation is done via the scalar (non-array) form of the delete operator: delete data; // deallocate memory assigned to data Note that the delete operator does not delete the pointer — it deletes the memory that the pointer points to. Also, if the programmer does not use the delete operator to deallocate memory, the system will crash as the memory will not be deallocated. This is called Memory Leak. Therefore, Dynamic memory allocation saves memory space by allocating only the necessary amount of space as required by the program at a given time, this increases its efficiency, reduces the runtime and makes the compilation much faster.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.